HDU 3639 Bone Collector II(01背包第K优解)

时间:2024-07-11 09:33:56

Bone Collector II

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4178    Accepted Submission(s): 2174

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

题目链接:HDU 2639

用in[]记录取第i的物品的答案,用out[]记录不取的答案,然后从in与out中寻找第1~k个值,放入dp[v][k]中……由于in与out至少在k范围内均是单调不增的序列,那只要判断一下重复的即可,相当于01背包多了个过程记录

代码:

#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<bitset>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
#define INF 0x3f3f3f3f
#define CLR(x,y) memset(x,y,sizeof(x))
#define LC(x) (x<<1)
#define RC(x) ((x<<1)+1)
#define MID(x,y) ((x+y)>>1)
typedef pair<int,int> pii;
typedef long long LL;
const double PI=acos(-1.0);
const int N=110;
const int K=35;
int w[N],c[N];
int in[K],out[K];
int dp[N*10][K];
void init()
{
CLR(in,0);
CLR(out,0);
CLR(dp,0);
}
int main(void)
{
int n,v,k,i,j,q;
int tcase;
scanf("%d",&tcase);
while (tcase--)
{
scanf("%d%d%d",&n,&v,&k);
init();
for (i=0; i<n; ++i)
scanf("%d",&w[i]);
for (i=0; i<n; ++i)
scanf("%d",&c[i]);
for (i=0; i<n; ++i)
{
for (j=v; j>=c[i]; --j)
{
for (q=1; q<=k; ++q)
{
in[q]=dp[j-c[i]][q]+w[i];
out[q]=dp[j][q];
}
int a=1,b=1,c=1;
in[k+1]=out[k+1]=-INF;
while (c<=k&&(in[a]!=-INF||out[b]!=-INF))
{
if(in[a]>out[b])
dp[j][c]=in[a++];
else
dp[j][c]=out[b++];
if(dp[j][c]!=dp[j][c-1])
++c;
}
}
}
printf("%d\n",dp[v][k]);
}
return 0;
}