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. SqlServer传输数据到ORACLE,SSIS

    一.配置32位ODBC 配置tnsname文件,增加ORACLE数据库 打开32位ODBC 二.创建一个PROJECT并配置数据源 1.创建一个project 三.数据传输SSIS,工作流 四.为DT ...

  2. InstallShield Limited Edition for Visual Studio 2013 图文教程

    http://www.wuleba.com/?p=23892   原文链接

  3. Finereport集群配置

    增加配置文件cluster.xml 将配置包resource文件夹下的cluster.xml打开,如果没有cluster.xml,则新建一个,基本内容如下: <?xml version=&quo ...

  4. (转载)python2+selenium自动化测试系列(二)

    16.Selenium2+python自动化16-alert\confirm\prompt 17.Selenium2+python自动化17-JS处理滚动条 18.Selenium2+python自动 ...

  5. fastjson将json字符串转化成bean对象解析出错的检查方法

    我的情况是:解析第一层数据成功,解析第二层嵌套的数据失败.如: { "response": { "resultcode": "0", &qu ...

  6. vue路由的简单实例

    vue2.0 和 vue1.0 路由的语法还是有点稍微的差别,下面介绍一下vue-router 2的简单实例: <!DOCTYPE html> <html lang="en ...

  7. 转一下大牛的嵌入web页播放视频方法(转)

    来自:http://www.cnblogs.com/bandry/archive/2006/10/11/526229.html 在Web页中嵌入Media Player的方法比较简单,只要用HTML中 ...

  8. redis对比其余数据库

    Redis属于常见的NoSQL数据库或者说非关系数据库:Redis不使用表,她的数据库也不会预定义或者强制去要求用户对Redis存储的不同数据进行关联. 常见数据库对比: 和高性能键值缓存服务器mem ...

  9. HDU 5652(二分+广搜)

    题目链接:http://acm.hust.edu.cn/vjudge/contest/128683#problem/E 题目大意:给定一只含有0和1的地图,0代表可以走的格子,1代表不能走的格 子.之 ...

  10. Java Reflection

    Java语言的反射机制 1. Java反射的含义:获取应用中正在运行的Java对象. 2. Java反射机制: 在运行的程序中,对于任意的类,都可以知道这个类的属性.方法以及构造函数,对于任意对象都可 ...