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. linux提取指定字符的行列并生成新文件(awk命令)

    如图所示,命名为file文件的表头有BP.A1.TEST等 假如想提取含有"ADD"的行和该行对应列的"BP"和"P"值,则需要用到以下命令 ...

  2. java_method_下拉框成json

    List<String[]> proList=service.getUserList(); int nTotal=0; String proJson="["; proJ ...

  3. Linux 中 Vi 编辑器的简单操作

    Linux 中 Vi 编辑器的简单操作 Vi 编辑器一共有3种模式:命名模式(默认),尾行模式,编辑模式.3种模式彼此需要切换. 一.进入 Vi 编辑器的的命令 vi  filename //打开或新 ...

  4. 自定义UISearchBar

    先上系统默认的UISearchBar,然后用KVO修改 UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:_topView.boun ...

  5. Python模块:struct

    各个编程语言都有自己的数据类型,当python需要接受其他语言或者网络传输来交互数据的时候,需要考虑到python的数据类型与其他平台之间交互问题.而python的struct就是解决这个问题的. s ...

  6. 在ubuntu 16.04系统环境中搭建NAS(samba/iscsi/nfs)

    在ubuntu 16.04系统中搭建NAS环境 一.基本配置1:设置静态IPvi /etc/network/interfaces#iface ens32 inet dhcpiface ens32 in ...

  7. myeclipse性能优化

    1. 取消启动项.这个设置立竿见影.Window->Preferences->General->Startup and Shutdown, Plug-ins activated on ...

  8. ms sql server 在cmd中执行sqlcmd的时候报错

    cmd下直接输入sqlcmd会提示 错误: HResult 0x2,级别 16,状态 1命名管道提供程序: 无法打开与 SQL Server 的连接 [2].Sqlcmd: 错误: Microsoft ...

  9. 树莓派安装Transmission-daemon出现的问题

    1,安装时发现默认的源里面没有transmission-daemon包 pi@fynn:/etc/apt/sources.list.d $ sudo apt-get install transmiss ...

  10. PHP获取当前服务器信息的基本语句

    下面是PHP获取当前服务器信息的基本语句. PHP程式版本: <?PHP echo PHP_VERSION; ?> ZEND版本: <?PHP echo zend_version() ...