标签:01背包 put ems fine today res ons 循环 str
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
这是之前写的题解 http://blog.csdn.net/hello_sheep/article/details/76246840
现在又来写一遍,感觉又有新的感悟~~见注释~
#include<stdio.h> #include<string.h> #define V 1100 #define K 35 #define N 110 int n,v,k; int dp[V][K],a[K],b[K],value[N],cost[N]; int main() { int i,j,l,t,s1,s2,s; scanf("%d",&t); while( t--) { scanf("%d%d%d",&n,&v,&k); for(i = 1; i <= n; i ++) scanf("%d",&value[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 --) { s = 0; for(l = 1; l <= k; l ++) { a[l] = dp[j][l]; b[l] = dp[j-cost[i]][l]+value[i]; } a[l] = b[l] = -1; //结尾赋值为-1的目的是保证a或b循环到结尾时,令b或a继续赋值给dp for(s1 = s2 = 1,l = 1; (s1<=k||s2<=k)&&l<= k;) {//只有a和b还有dp都到结尾时,才能够结束循环 if(a[s1] > b[s2]) dp[j][l] = a[s1++]; else dp[j][l] = b[s2++]; if(dp[j][l] != dp[j][l-1])//保证有序队列中没有重复的 ++l; } } printf("%d\n",dp[v][k]); } return 0; }
【背包专题】A - Bone Collector II hdu2639 【01背包的第k个最优解】
标签:01背包 put ems fine today res ons 循环 str
原文地址:http://www.cnblogs.com/chengdongni/p/7422216.html