Accepted Necklace
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2530 Accepted Submission(s): 999
Problem Description
I have N precious stones, and plan to use K of them to make a necklace for my mother, but she won‘t accept a necklace which is too heavy. Given the value and the weight of each precious stone, please help me find out the most valuable necklace my mother will accept.
Input
The first line of input is the number of cases.
For each case, the first line contains two integers N (N <= 20), the total number of stones, and K (K <= N), the exact number of stones to make a necklace.
Then N lines follow, each containing two integers: a (a<=1000), representing the value of each precious stone, and b (b<=1000), its weight.
The last line of each case contains an integer W, the maximum weight my mother will accept, W <= 1000.
Output
For each case, output the highest possible value of the necklace.
Sample Input
1
2 1
1 1
1 1
3
Sample Output
1
题意:就是你有n个宝石,想用k个做成一个项链送给你妈妈,每个宝石的价值和重量都不一样,你可以选择几个做成项链,但重量不能超过w,并且要得到的价值最大。
解题思路:一看就是一个贪心背包问题,用dp的思想来解决。在重量和个数直接取价值最大。
贴出代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int n, k, w,T; int value[25], weight[25], num[1005][25]; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &k); memset(num, 0, sizeof(num)); for(int i = 0; i<n; i++) { scanf("%d%d", &value[i], &weight[i]); } scanf("%d", &w); for(int i = 0; i<n; i++) { for(int j = k; j>0; j--) { for(int x = w; x>=weight[i]; x--) { if(num[x][j] < num[x-weight[i]][j-1]+value[i]) num[x][j] = num[x-weight[i]][j-1]+value[i]; } } } printf("%d\n", num[w][k]); } return 0; }
hdu 2660 Accepted Necklace (二维背包)