Bone Collector II
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2435 Accepted Submission(s): 1278
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 2
31).
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
Author
teddy
Source
百万秦关终属楚
#include<stdio.h>
#include<string.h>
#define max(A,B) (A)>(B)?A:B
int main()
{
int T;
while(scanf("%d", &T) != EOF){
while(T--)
{
int n, V, vo[110], va[110], k;
scanf("%d%d%d", &n, &V, &k);
for(int i = 1; i <= n; i++)
scanf("%d", &va[i]);
for(int i = 1; i <= n; i++)
scanf("%d", &vo[i]);
int f[1100][35], a[110],b[110];
memset(f, 0, sizeof(f));
for(int i = 1; i <= n; i++)
{
for(int j = V; j >= vo[i]; j--)//求出第i个物品的前k个最优解
{
for(int l = 1; l <= k; l++)
{
a[l] = f[j][l];//保存前一轮的最优解
b[l] = f[j - vo[i]][l] + va[i];//保存这轮的最优解
}
int x, y, z;
x = y = z = 1;
a[k+1] = -1;
b[k+1] = -1;
while(z <= k && (a[x] != -1 || b[y] != -1))//当k小于总的最优解个数时 z<=k 提前结束
{ //当k大于总的最优解个数时,以a,b数组的结束符终止循环
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++;
}
}
}
printf("%d\n", f[V][k]);
}
}
return 0;
}
题意:给出一个容量为V的背包,往背包里放东西,每个东西都占据一定的空间,并且每个东西都有一个价值,求往背包里放东西能取得最大的价值,现求能取得的第k个最大值。
思路:对于每一个物品始终只有放与不放,先求出每一个物品放与不放时所能得到的一系列价值,这里假设第i个物品,会得到f【i】【】【】一系列的价值,再考虑下一个物品又能得到一系列新的价值f【i+1】【】【】,分别记录这两组价值数,再将其比较合并,将不同的值从小到大重新放回f数组里。最终得到的便是当所有物品都考虑完后,背包里
最终所能得到的一系列最优解,取出第k个输出就是了。这里由于数V是逆序的,所以省略了f的一维。