Bone Collector II(0 1背包求第k优解)
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2639
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6738 Accepted Submission(s): 3580
Problem Description
The title of this problem is familiar,isn’t it?yeah,if you had took part in the “Rookie Cup” competition,you must have seem this title.If you haven’t seen it before,it doesn’t matter,I will give you a link:
.
Here is the link:http://acm.hdu.edu.cn/showproblem.php?pid=2602
.
Today we are not desiring the maximum value of bones,but the K-th maximum value of the bones.NOTICE that,we considerate two ways that get the same value of bones are the same.That means,it will be a strictly decreasing sequence from the 1st maximum , 2nd maximum … to the K-th maximum.
.
If the total number of different values is less than K,just ouput 0.
Input
The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, K(N <= 100 , V <= 1000 , K <= 30)representing the number of bones and the volume of his bag and the K we need. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.
Output
One integer per line representing the K-th maximum of the total value (this number will be less than 231).
Sample Input
3
5 10 2
1 2 3 4 5
5 4 3 2 1
5 10 12
1 2 3 4 5
5 4 3 2 1
5 10 16
1 2 3 4 5
5 4 3 2 1
Sample Output
12
2
0
题解
输入N个数据,背包容量为V,求第K优解
题目思路:
先定义二维数组dp [1105][35],第二维用来记录第k优解
a[35],b[35],用来暂时储存dp的所有解,
然后再把所有解从大到小排序赋值给dp,最后得出答案
话不多说,奉上代码
#include<iostream>
#include<string.h>
#define max(a,b) a>b?a:b;
#define min(a,b) (a>b?b:a)
int n,sum,k,w[110],v[110],dp[1105][35],a[35],b[35];
int main()
{
int T;
while(scanf("%d",&T)!=EOF)
{
while(T--)
{
memset(dp,0,sizeof(dp));
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
scanf("%d %d %d",&n,&sum,&k);
for(int i=1;i<=n;i++)
scanf("%d",&v[i]);
for(int i=1;i<=n;i++)
scanf("%d",&w[i]);
for(int i=1;i<=n;i++)
{
for(int j=sum;j>=w[i];j--)
{
for(int z=1;z<=k;z++) //记录所有结果
{
a[z]=dp[j][z];
b[z]=dp[j-w[i]][z]+v[i];
}
a[k+1]=-1;
b[k+1]=-1;
for(int x=1,y=1,z=1;z<=k && (a[x]!=-1 || b[y]!=-1);)//所有解由最优到不优排列;
{
if(a[x]>b[y])
{
dp[j][z]=a[x];
x++;
}
else
{
dp[j][z]=b[y];
y++;
}
if(dp[j][z]!=dp[j][z-1])//筛选重复解;
{
z++;
}
}
}
}
printf("%d\n",dp[sum][k]);
}
}
return 0;
}