Knapsack Problem--nyoj Topic 106

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.