HDU-2639 Bone Collector II
Posted ISGuXing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU-2639 Bone Collector II相关的知识,希望对你有一定的参考价值。
Bone Collector II
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4948 Accepted Submission(s): 2588Problem DescriptionThe 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 231).
Sample Input35 10 21 2 3 4 55 4 3 2 15 10 121 2 3 4 55 4 3 2 15 10 161 2 3 4 55 4 3 2 1Sample Output1220
这道题的题目大意就是求第k个优解。当然是逆序,就想当于 我们平时求的最优解是第一个,然后递减。
这道题目有助于更好的理解动态规划的一个过程问题。
刚入门的时候并不知道动态规划里面到底是怎么样的一个过程。
代码第一次看,可能会有点节奏快,慢慢来,别急。
当你彻底想明白的时候,那么相信你对动态规划的理解会更深!
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 using namespace std; 5 6 struct Node 7 { 8 int price; 9 int val; 10 } node[1005]; 11 12 int main() 13 { 14 int t; 15 scanf("%d",&t); 16 while(t--) 17 { 18 int n,v,k,i,dp[1005][31] = {0},a[31],b[31]; 19 scanf("%d%d%d",&n,&v,&k); 20 for(i = 0; i<n; i++) 21 scanf("%d",&node[i].price); 22 for(i = 0; i<n; i++) 23 scanf("%d",&node[i].val); 24 int j; 25 for(i = 0; i<n; i++) 26 { 27 for(j = v; j>=node[i].val; j--) 28 { 29 int cnt = 0,d; 30 for(d = 1; d<=k; d++)//分别将放入第i个石头与不放第i个石头的结果存入a,b,数组之中 31 { 32 a[d] = dp[j-node[i].val][d]+node[i].price; 33 b[d] = dp[j][d]; 34 } 35 int x,y,z; 36 x = y = z = 1; 37 a[d] = b[d] = -1; //边界!!!因为下面循环的时候会造成越过d-1; 38 while(z<=k && (x<=k || y<=k))//循环找出前K个的最优解 ,这个循环很关键啊 39 { 40 if(a[x] > b[y]) 41 { 42 dp[j][z] = a[x]; 43 x++; 44 } 45 else 46 { 47 dp[j][z] = b[y]; 48 y++; 49 } 50 if(dp[j][z]!=dp[j][z-1]) //判断有没有重复,重复就不计录下来 51 z++; 52 } 53 } 54 } 55 printf("%d\n",dp[v][k]); 56 } 57 58 return 0; 59 }
以上是关于HDU-2639 Bone Collector II的主要内容,如果未能解决你的问题,请参考以下文章
HDU2639Bone Collector II[01背包第k优值]
HDU 2639 Bone Collector II(01背包变形第K大最优解)