Bone Collector II
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
题目大意:
t组输入,输入三个数n,m,k分别表示骨头的数量、包的体积和最优解k。然后输入n行表示骨头的价值,再输入n行表示骨头的体积。求体积为m的第k最大值。
思路:
01背包 + 第k优解
现在01的基础上多加一维,f[m][k]
,表示在m空间下第k大的价值。
更新的时候有两个数组a
、b
,a
记录选择第i个物品的从大到小排列,b
记录不选择的从大到小排列,然后合并ab
,选出ab
里面前k个最大的。合并到f
中。
完整代码:
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1010, M = 35;
int f[N][M];
int v[N],w[N]; // 骨头的体积,价值
int n,m,k; // 骨头的数量;包的体积;最优解k
int a[N],b[N]; // 存储放和不放两种状态,a[]为放,b[]为不放
int main()
{
int t;
cin>>t;
while(t--)
{
memset(f,0,sizeof f);
cin>>n>>m>>k;
for(int i=1;i<=n;i++) cin>>w[i];
for(int i=1;i<=n;i++) cin>>v[i];
for(int i=1;i<=n;i++)
{
for(int j=m;j>=v[i];j--)
{
int x,y,z,s;
for(s=1;s<=k;s++) // 分别将放入第i个石头与不放第i个石头的结果存入a,b,数组之中
{
a[s]=f[j-v[i]][s]+w[i]; // 放
b[s]=f[j][s]; // 不放
}
x=y=z=1;
a[s]=b[s]=-1;
while(z<=k && (x<=k || y<=k)) // 循环找出前K个的最优解
{
if(a[x]>b[y])
{
f[j][z]=a[x];
x++;
}
else
{
f[j][z]=b[y];
y++;
}
if(f[j][z]!=f[j][z-1]) z++;
}
}
}
cout<<f[m][k]<<endl;;
}
return 0;
}