hdu 2639 【01背包的第k个最优解】

Bone Collector II



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
 
01背包的第k个最优解
题意:输入t,再输入t组样例,每组样例输入三个数,n,v,k,接下来一行输入n个数代表物体质量,再下一行输入n个数代表物体体积,输出v体积下的第k个最优解。
   
思路:要使dp[i][V][1....k]这k个数是由大到小排列,则找出每个物品状态下的最优解, 已知dp[i][v][1..k] 由dp[i-1][v][1..k]合并而来,那么只要合并到第n个物品即dp[n] [v][1....k]就是我们求得最后的最优状态。
用01背包的思路可以去掉一维,因为循环是从v...0,故dp[j][1..k]实质是dp[i- 1][j][1..k],由于这道题把策略不同但权值相同的两个方案看做同一个解,所以 还需要进行去重处理,如下。

反思:下次再也不手动初始化数组,明明是0~N-1,我写成0~N,直接溢出,这个低级 bug让我从早上7点找到现在 ,宝贵的时间就这样没了。 

#include<stdio.h>
#include<string.h>
#define N 1010

int dp[N][N];
int w[N],cost[N],a[N],b[N];

int main()
{
	int t,n,m,k,V;
	int i,j;
	int l,x;
	scanf("%d",&t);
	while(t --)
	{
		
		scanf("%d%d%d",&n,&V,&k);
		for(i = 1; i <= n; i ++)
			scanf("%d",&w[i]);
		for(i = 1; i <= n; i ++)
			scanf("%d",&cost[i]);
		memset(dp,0,sizeof(dp));	
		for(i = 1; i <= n; i ++)
		{
			for(j = V; j >= cost[i]; j --)
			{
				for(m = 1; m <= k; m ++)
				{
					a[m] = dp[j][m];
					b[m] = dp[j-cost[i]][m]+w[i];
				}
				a[m] = -1;
				b[m] = -1;
				for(m = 1,x = 1,l = 1; (l<=k||x<= k)&&m <= k;)
				{
					if(a[x] > b[l])
					{
						dp[j][m] = a[x];
						x++;
					}
					else
					{
						dp[j][m] = b[l];
						l++;
					}
					if(dp[j][m-1]!=dp[j][m])
						m++;	
				}
			}
		}
		printf("%d
",dp[V][k]);
	}
	return 0;
}


原文地址:https://www.cnblogs.com/hellocheng/p/7350103.html