Problem Introduction

Given a set of items and total capacity of a knapsack,find the maximal value of fractions of items that fit into the knapsack.

Problem Description

Task.The goal of this code problem is to implement an algorithm for the fractional knapsack problem.

Input Format.The first line of the input contains the number \(n\) of items and the capacity \(W\) of a knapsack.The next \(n\) lines define the values and weights of the items. The \(i\)-th line contain integers \(v_i\) and \(w_i\)—the value and the weight of \(i\)-th item,respectively.

Constraints.\(1 \leq n \leq 10^3, 0 \leq W \leq 2 \cdot 10^6; 0 \leq v_i \leq 2 \cdot 10^6, 0 < w_i \leq 2 \cdot 10^6\) for all \(1 \leq i \leq n.\) All the numbers are integers.

Output Format.Output the maximal value of fractions of items that fit into the knapsack.The absolution value of the difference between the answer with at least four digits after the decimal point(otherwise your answer,while being computed correctly,can turn out to be wrong because of rounding issues).

Sample 1.
Input:

3 50
60 20
100 50
120 30

Output:

180.0000

Sample 2.
Input:

1 10
500 30

Output:

166.6667

Solution

# Uses python3
import sys
import numpy as np

def get_optimal_value(capacity, weights, values):
    value = 0.
    indices = np.argsort([-v/w for w,v in zip(weights,values)])
    for idx in indices:
        if capacity <= 0:
            break
        weight = min(capacity, weights[idx])
        capacity -= weight
        value +=  weight * (values[idx] / weights[idx])
    return value

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    n, capacity = data[0:2]
    values = data[2:(2 * n + 2):2]
    weights = data[3:(2 * n + 2):2]
    opt_value = get_optimal_value(capacity, weights, values)
    print("{:.10f}".format(opt_value))

[UCSD白板题] Fractional Knapsack的更多相关文章

  1. [UCSD白板题] Take as Much Gold as Possible

    Problem Introduction This problem is about implementing an algorithm for the knapsack without repeti ...

  2. [UCSD白板题] Longest Common Subsequence of Three Sequences

    Problem Introduction In this problem, your goal is to compute the length of a longest common subsequ ...

  3. [UCSD白板题] Maximize the Value of an Arithmetic Expression

    Problem Introduction In the problem, your goal is to add parentheses to a given arithmetic expressio ...

  4. [UCSD白板题] Compute the Edit Distance Between Two Strings

    Problem Introduction The edit distinct between two strings is the minimum number of insertions, dele ...

  5. [UCSD白板题] Primitive Calculator

    Problem Introduction You are given a primitive calculator that can perform the following three opera ...

  6. [UCSD白板题] Points and Segments

    Problem Introduction The goal in this problem is given a set of segments on a line and a set of poin ...

  7. [UCSD白板题] Number of Inversions

    Problem Introduction An inversion of a sequence \(a_0,a_1,\cdots,a_{n-1}\) is a pair of indices \(0 ...

  8. [UCSD白板题] Sorting: 3-Way Partition

    Problem Introduction The goal in this problem is to redesign a given implementation of the randomize ...

  9. [UCSD白板题] Majority Element

    Problem Introduction An element of a sequence of length \(n\) is called a majority element if it app ...

随机推荐

  1. SQL联合查询两个表的数据

    刚有个项目,需要查询水位数据表中的水位信息,及查询降雨量表中统计时段降雨量的数据,以计算出日降雨量,而且时段是前一天8时到后一天8时总共24个小时. 两个子查询: 1.根据当前时间判断统计前天8时到今 ...

  2. QT征程之初识qt

    下载 https://www.qt.io/cn/download-open-source/     下载QT离线安装包 Qt 5.5.1 for Linux 32-bit (546 MB) (info ...

  3. 郑捷《机器学习算法原理与编程实践》学习笔记(第四章 推荐系统原理)(二)kmeans

    (上接第二章) 4.3.1 KMeans 算法流程 算法的过程如下: (1)从N个数据文档随机选取K个文档作为质心 (2)对剩余的每个文档测量其到每个质心的距离,并把它归到最近的质心的类 (3)重新计 ...

  4. android 内存问题

    借鉴:大苞米的博客(http://blog.csdn.net/a396901990) 一.内存溢出(OOM--out of memory) (1)内存溢出引发的问题展现: 1.程序卡顿,响应速度慢(内 ...

  5. hashchange事件的认识

    写过路由的同学都知道其原理是通过URL的改变,由导航信息来决定页面信息...表述的好像有点不准确 这么说吧,只要URL参数列表只要变化就会调用hashchange事件,此时event对象包括oldUR ...

  6. ArcMap中地图输出(Options)选项显示不完整

    首先,我开始遇到的时候,认为是高分辨屏幕的问题,所以修改了屏幕的分辨率,结果并没有改变. 然后,认为是对话窗口的显示,修改字体大小,也没有显示完整. 最后,是修改了ArcGIS的注册表才解决.解决方式 ...

  7. Docker学习<一>--初体验Windows环境下安装

    背景 今天想试用spring boot与jwt协议的实现,配套就需要使用redis,但redis似乎windows环境版本部署起来不是那么舒心,果断尝试使用docker. 下载 下载地址: 稳定版:h ...

  8. nginx+tomcat负载均衡

    最近练习nginx+tomcat负载均衡.根据一些资料整理了大体思路,最终实现了1个nginx+2个tomcat负载均衡. 安装JDK 1>进入安装目录,给所有用户添加可执行的权限 #chmod ...

  9. mysql备份文件注释乱码处理工具

    我们有时候需要做mysql数据库的注释,可是备份出来的是乱码,怎么办呢? 本工具软件来帮你的忙. 将GBK库备份后的文本文件中夹带的UTF8乱码转换为GBK编码,就不再乱码了. http://down ...

  10. some things

    ////html[1]/body[1]/div[9]/div[1]/div[1]/div[1]/ul/li  截取规则 Articles/Article[1]:选取属于Articles子元素的第一个A ...