Knapsack Problem time limit:MS | Memory limit:65535 KB 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 I give you a backpack, it can hold a weight of M (10<=m<=20), All you have to do is pack the items into your backpack so that the value of the items in your 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
This problem is obviously the greedy algorithm, the value of high-end to take the low value;
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 6 struct as7 {8 intv;9 intW;Ten}aa[ One]; One A - BOOLcmp asX asy) - { the returnx.v>y.v;//sort by value from top to bottom - } - intMain () - { + intn,s,m,i; -scanf"%d",&n); + while(n--) A { atscanf"%d%d",&s,&m); - for(i=0; i<s;i++) -scanf"%d%d",&aa[i].v,&AA[I].W); -Sort (aa,aa+s,cmp); - intsum=0; - for(i=0; i<s;i++) in { - if(m>=AA[I].W) to { +sum+=aa[i].v*AA[I].W; -m-=AA[I].W; the } * Else $ {Panax Notoginsengsum+=m*aa[i].v; - Break; the } + } Aprintf"%d\n", sum); the } + return 0; -}
Knapsack Problem--nyoj Topic 106