您的位置:首页 > 其它

HDU-2639(01背包+求第k个最大值)

2017-07-24 17:28 225 查看
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.

InputThe 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. 

OutputOne 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
12
2
0


/*
题意:同上一篇HDU-2602
只不过多了一个k表示第k个最大值解

分析:
我找了一下有一篇博客讲的不错,直接复制过来了。

简单的01背包基础上做,要求的是第K个最大值,
那么不用dp[j]=max(dp[j],dp[j-w[i]]+v[i])的状态转移方程,
而是将两个值都记录下来,用for循环走一遍,记录下,容量
为1到M的各个最大价值,dp[i][j]表示当背包容量为i时的第j个
最大价值,最后只需要输出dp[m][k]即可!
*/
#include <stdio.h>
#include <string.h>
#include<iostream>
#include <algorithm>
#include<math.h>
#include<map>
using namespace std;
#define MEM(a) memset(a,0,sizeof(a))

int dp[1005][31];//dp[i][j]表示容量为i的第j个最大解
int w[1005];
int v[1005];
int dp1[1005];
int dp2[1005];

int main()
{
int t;
cin >> t;
int n, m, k;
int p;
int x1, x2, kk;
while (t--)
{
MEM(dp);
MEM(dp1);
MEM(dp2);
MEM(w);
MEM(v);
cin >> n >> m >> k;
for (int i = 0; i < n; i++)
{
cin >> w[i];
}
for (int i = 0; i < n; i++)
{
cin >> v[i];
}

for (int i = 0; i < n; i++)
{
for (int j = m; j >= v[i]; j--)
{
for (p = 1; p <= k; p++)
{
dp1[p] = dp[j][p];
dp2[p] = dp[j - v[i]][p] + w[i];
}
dp1[p] = dp2[p] = -1;
x1 = x2 = kk = 1;

while ((dp1[x1] != -1 || dp2[x2] != -1) && kk <= k)
{
if (dp1[x1] > dp2[x2])
{
dp[j][kk] = dp1[x1];
x1++;
}
else
{
dp[j][kk] = dp2[x2];
x2++;
}
if (dp[j][kk - 1] != dp[j][kk])
{
kk++;
}

}

}
}
cout << dp[m][k] << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: