R6-1 Knapsack
分数 8
作者 王灿
单位 浙江大学

Given nn items, where the ii-th one has weight wiw_i and value viv_i. We only have a knapsack with capacity WW which might not be large enough to hold all the items. Fortunately, we can use magic — for item ii, each time the magic can reduce its weight by 11 for the cost of cic_i. On the other hand, the weight of any item must always be positive — meaning that we cannot use magic to reduce the weight to 0 or less. We can use the magic any number of times. The profit of packing item ii into the knapsack is viki×civ_i - k_i\times c_i where kik_i is the number of times we apply the magic on item ii.

The question is: what is the maximum profit we can get?

It is guaranteed that 1n200,1W200,1wi200,1vi106,1ci1061\le n\le 200, 1\le W\le 200,1\le w_{i} \le 200,1\le v_{i} \le 10^6, 1\le c_{i} \le 10^6.

Function Interface:

int knapsack(int n, int W, int w[], int v[], int c[]);

where n represents the number of items. W represents the capacity of the knapsack. The arrays w[0…n-1],v[0…n-1],c[0…n-1] are the weights, values, and costs of the items.

Judge Program:

#include <stdio.h> int knapsack(int n, int W, int w[], int v[], int c[]); const int maxn = 200; int main() { int n, W; int v[maxn], w[maxn], c[maxn]; scanf(“%d %d”, &n, &W); for(int i = 0; i < n; i++) scanf(“%d%d%d”, &w[i], &v[i], &c[i]); printf(“%d\n”, knapsack(n, W, w, v, c)); return 0; } /* Fill your program here*/

Sample Input:

4 10
8 10 2
12 15 3
5 9 2
3 8 1

Sample Output:

17

代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C++ (g++)
int max(int a,int b){
return (a>b)?a:b;
}
int min(int a,int b){
return (a<b)?a:b;
}

int knapsack(int n, int W, int w[], int v[], int c[]){
int pack[W];
for (int i=0;i<=W;i++){
pack[i]=0;
}
int max_weight=0;
for (int i=0;i<n;i++){
int nowweight=w[i];
max_weight+=nowweight;
if (max_weight>W){
max_weight=W;
}
for (int j=W;j>=1;j--){
for (int k=1;k<=min(nowweight,j);k++){

int nowvalue=v[i]-(nowweight-k)*c[i];
pack[j]=max(pack[j],pack[j-k]+nowvalue);
}
}
}

return pack[W];
}
退出答题
Code Completion
当前1 - 1项,共1项