nyoj~106~ knapsack problem ~ greedy algorithm ~

Source: Internet
Author: User

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 ~

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.