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 has n test data, and the first row of each set of test data has two positive integers s,m (1&l T;=S<=10); s indicates that there is an S item. The next S-line has two positive integer v,w per line. The
-
output
-
outputs the value of the items in the backpack in each set of test data, and each output takes up one row.
-
Sample Input
-
13 155 102 9
-
sample output
-
65
-
ac-code:
#include <stdio.h> #include <algorithm>using namespace std;struct Bag{int v;int W;}; BOOL CMP (bag A,bag b) {return A.V>B.V;} int main () {int sum,s,m,i,max,n;bag a[100];scanf ("%d", &n), while (n--) {scanf ("%d%d", &s,&m); for (i=0;i< s;i++) scanf ("%d%d", &A[I].V,&A[I].W); Max=m;sum=0;sort (a,a+s,cmp); for (i=0;i<s;i++) {if (A[i].w<=max) {SUM+=A[I].V*A[I].W;MAX-=A[I].W;} Else{sum+=a[i].v*max;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 ~ greedy algorithm ~