HDU - 2660
题面:
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颗为我妈妈做一条项链,但她不会接受太重的项链。
鉴于每颗宝石的价值和重量,请帮我找出我妈妈会接受的最有价值的项链。
输入
输入的第一行是用例的数量。对于每种情况,第一行包含两个整数N (N <= 20),即石头的总数,和K (K <= N),即制作项链的确切石头数。
然后是N行,每一行包含两个整数:a (a<=1000)表示每颗宝石的价值,b (b<=1000)表示其重量。每种情况的最后一行包含一个整数W, W是我母亲将接受的最大权值,W <= 1000。输出对于每种情况,输出项链的最高可能值。
输出
对于每种情况,程序都必须在输出文件的单独行上打印结果。如果没有回答,打印0。
思路
我这个菜鸡不会用深度搜索来写这题,用的是动态规划,关键是这条回归方程gg[z][j]=gg[z-b[i]][j-1]+a[i];主要就是判断在z质量 j物品的情况下放入物品是否有更高的价值,比较经典的背包问题。
代码
#include<iostream>
#include<cstring>
using namespace std;
int a[1001],b[1001],gg[1001][21];//gg当前选取的宝石的编号
int main()
{
int t,n,k,w,x,y,z,zz;//x当前宝石总值 ,y当前宝石总质量 ,z为预订要替换的位置 ,zz为预订替换后的总值
cin>>t;
while(t--)
{
cin>>n>>k;
for(int i=1;i<=n;i++)
{
cin>>a[i]>>b[i];
}
cin>>w;
for(int i=1;i<=n;i++)
{
for(int z=w;z>=b[i];z--)
{
for(int j=1;j<=k;j++)
{
if(gg[z-b[i]][j-1]+a[i]>gg[z][j])
gg[z][j]=gg[z-b[i]][j-1]+a[i];
}
}
}
cout<<gg[w][k]<<endl;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(gg,0,sizeof(gg));
}
return 0;
}