Knapsack Problem time limit: theMs | Memory Limit:65535KB Difficulty:3
-
-
Describe
-
Now there are a lot of items (they are divisible), we know the value of each unit weight of each item V and the weight w (1<=v,w<=10); If you give you a backpack, it can hold a weight of M (10<=m<=20), all you have to do is pack the items in your backpack. , so that the total value of the items in the backpack is the largest.
-
-
Input
-
-
The first line enters a positive integer n (1<=n<=5), which indicates that there are n sets of test data;
Then there are n test data, the first line of each set of test data has two positive integers s,m (1<=s<=10); s indicates that there is an S item. The next S-line has two positive integer v,w per line.
-
-
Output
-
Outputs the value of the items in the
-
backpack for each set of test data and each output takes up one row.
-
-
Sample input
-
-
13 155 102) 83 9
-
-
Sample output
-
-
65
-
-
/* greedy. Part of the knapsack problem. */#include <cstdio> #include <algorithm>using namespace std;const int maxn = 20;struct res{int v,w;} Arr[maxn];int S,m;bool cmp (res x,res y)//value from small to large sort {return x.v>y.v;} int main () {int n,i,sum;scanf ("%d", &n), while (n--) {scanf ("%d%d", &s,&m), for (I=0;i<s;++i) {scanf ("%d%d ", &ARR[I].V,&ARR[I].W);} Sort (arr,arr+s,cmp); Sum=0;for (i=0;i<s;++i) {if (m-arr[i].w>0)//can take out all of the {SUM+=ARR[I].V*ARR[I].W;M-=ARR[I].W;} else//cannot be completed, take part {sum+=m*arr[i].v;break;}} printf ("%d\n", sum);} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Nyoj 106 knapsack problem