【背包专题】A

来源:互联网 发布:淘宝开店需要押金吗? 编辑:程序博客网 时间:2024/06/05 02:22
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

35 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 1

Sample Output

1220这是之前写的题解  http://blog.csdn.net/hello_sheep/article/details/76246840现在又来写一遍,感觉又有新的感悟~~见注释~
#include<stdio.h>#include<string.h>#define V 1100#define K 35#define N 110int 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;}