您的位置:首页 > 其它

HDU 2639 01背包求第k大

2016-04-28 00:00 447 查看

Bone Collector II

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


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
One integer per line representing the K-th maximum of the total value (this number will be less than 231).

[align=left]Sample Input[/align]

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

[align=left]Sample Output[/align]

12

2
0

[align=left]Author[/align]
teddy

[align=left]Source[/align]
百万秦关终属楚

题意:2602的改版 与普通01背包不同是求第k大价值

题解:增加一维 存储 dp[i][w] 容量为i的背包存放的物品的第w大价值和
增加一步 两个序列合并的过程 形成新的k大

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#define ll __int64
#define pi acos(-1.0)
#define mod 1
#define maxn 10000
using namespace std;
int t;
int n,v,k;
int a[105];
int b[105];
int we[105],va[105];
int dp[1005][105];
int main()
{
while(scanf("%d",&t)!=EOF)
{
for(int i=1;i<=t;i++)
{
memset(we,0,sizeof(we));
memset(va,0,sizeof(va));
memset(dp,0,sizeof(dp));
scanf("%d %d %d",&n,&v,&k);
for(int j=1;j<=n;j++)
scanf("%d",&we[j]);
for(int j=1;j<=n;j++)
scanf("%d",&va[j]);
for(int j=1;j<=n;j++)
{
for(int l=v;l>=va[j];l--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(int m=1;m<=k;m++)
{
a[m]=dp[l][m];
b[m]=dp[l-va[j]][m]+we[j];
}
a[k+1]=-1;
b[k+1]=-1;
int x=1,y=1,w=1;
while(w<=k&&(x<=k||y<=k))//合并的过程
{
if(a[x]>b[y])
{
dp[l][w]=a[x];
x++;
}
else
{
dp[l][w]=b[y];
y++;
}
if(w==1||dp[l][w]!=dp[l][w-1])
w++;
}
}
}
cout<<dp[v][k]<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: