Bone Collector II
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2464 Accepted Submission(s): 1295 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 Input3 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 1Sample Output
12 2 0
题意:给你n个骨头的信息(价值和体积),给你一个体积为V的背包,要你求出这个背包装骨头得到的所有价值中第K大的
思索了半天不知道就百度,百度之后还是不懂结果就看接替报告,看了半天看是不知道博主们想说的是什么,于是就对照代码对照数据事劲瞅,然后才差不多懵懵懂
解析:常规的01背包是求的V体积的容器中装物品得到的最大价值,像这个要求的是第K大的就有点力不从心了,所以要加点料,背包九讲里边学来的公式是
f[x]=max[f[x-v]+w,f[x]),要求K大的值肯定要记录更多数据才行,所以给数组加一维变成f[ ][ ],第二维里面就用来记录K个数据,分别是最大递减到K大,然后直接用01背包的方法求就是了,本来f[x][1~k]中只有K个数据,对于1~k全部都作上面的那个公式处理一下,然后得到的数据是2*K个,懂吧?分别是f[x][k]和f[x-v][k]+w,然后这些数据取最大的K个记录下来就行了
其实这个我还是不太懂,验证了半天就是得不出让我心安理得的结论,为什么这样就能保证结果中能得出所有值,其中的一些小插曲就不说了,看代码吧!
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int main (void) { int n,v,m,i,j,k,l,t; __int64 dp[1111][33],a[2][33],vol[111],val[111]; scanf("%d",&t); while(t--&&~scanf("%d%d%d",&n,&v,&m)) { for(i=0;i<n;i++) { scanf("%I64d",&val[i]); } for(i=0;i<n;i++) { scanf("%I64d",&vol[i]); } memset(dp,0,sizeof(dp)); for(i=0;i<n;i++) { for(j=v;j>=vol[i];j--) { for(k=0;k<m;k++) //把第二维里面的每个数据都记录一个继承值和优选值 { a[0][k]=dp[j][k]; //不选择装入第i个物品 a[1][k]=dp[j-vol[i]][k]+val[i]; //装入第i个物品 } int p,q,w; p=q=w=0; a[0][m]=a[1][m]=-1; //考虑会出现其中一个数组的去完了的情况,所以末尾-1有妙用 while(w<m&&(p<m||q<m)) { if(a[0][p]<a[1][q]) { dp[j][w]=a[1][q]; q++; }else { dp[j][w]=a[0][p]; p++; } if(w==0||dp[j][w]!=dp[j][w-1]) //有重复值 w++; } } } printf("%I64d\n",dp[v][m-1]); } return 0; }
总结:这算是一个新的写法,至少对于我来说,我还没有真正弄懂这个做法,只是简单的记下来了,记下来是没用的,要理解才行,这两天就多瞅瞅吧,直到弄明白了再说!
时间: 2024-10-02 20:35:13