hdu 2639 Bone Collector II(求第k优解 01背包)

来源:互联网 发布:php java性能 编辑:程序博客网 时间:2024/05/15 00:56

Bone Collector II

链接http://acm.hdu.edu.cn/showproblem.php?pid=2639


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

题意:有n件物品,每件物品有体积和价值已知, 一个小偷带着一个大小为v的背包,要偷这些东西,问小偷能偷的第k大的价值是多少?
解析:这题和典型的01背包求最优解不同,是要求第k大的解,所以,最直观的想法就是在01背包的基础上再增加一维,用来保存前k大小的数,然后         在递推时,根据前一个状态的前 k 大的数推出下一个阶段的前k个数保存下来。
       d[i][j][k], 表示取前i个物品,用j的费用,第k大价值是多少
        在递推dp[i][v][1...k]时,先获取上一个状态d[i-1][j][1...k]递推出来所有的值:

    即集合A={dp[i-1][j-v[i]][p]+w[i], 1<=p<=k}, 还有原来的值集合B={dp[i-1][j][p], 1<=p<=k}

    然后把集合A和B中的前k大的值按从大到小顺序赋值给d[i][j][1...k],

    这一步骤可以用归并排序中的合并方法,因为集合A和B一定是按照从大到小的顺序排列的。

AC代码:

#include<stdio.h>#include<string.h>struct stu{    int v,w;}a[105];int main(){    int i,j,k,T,m,n,v,x,y,z,dp[1005][35],d1[35],d2[35];    scanf("%d",&T);    while(T--){        scanf("%d%d%d",&n,&v,&k);        for(i=1;i<=n;i++)            scanf("%d",&a[i].w);        for(i=1;i<=n;i++)            scanf("%d",&a[i].v);        memset(dp,0,sizeof(dp));        memset(d1,0,sizeof(d1));        memset(d2,0,sizeof(d2));        for(i=1;i<=n;i++)            for(j=v;j>=a[i].v;j--){                for(m=1;m<=k;m++){                    d1[m]=dp[j][m];                    d2[m]=dp[j-a[i].v][m]+a[i].w;                }                d1[m]=d2[m]=-1;                x=y=z=1;                while((d1[x]!=-1||d2[y]!=-1)&&z<=k){                    if(d1[x]>d2[y])                        dp[j][z]=d1[x++];                    else                        dp[j][z]=d2[y++];                    if(dp[j][z-1]!=dp[j][z])                        z++;                }            }        printf("%d\n",dp[v][k]);    }    return 0;}

0 0