【HDU】 2639 Bone Collector II

来源:互联网 发布:复方雄蛾强肾胶囊淘宝 编辑:程序博客网 时间:2024/06/16 13:13

Bone Collector II

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3411    Accepted Submission(s): 1758


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

 题解:这一题感觉不是很容易想到,要求背包第K大的价值。我们通俗的01背包是保留当前状态下的最好决策,比如最大或最小。但是这里要求第K大的价值,我们用单纯的01背包肯定是算不出来的,因为有一些不优的状态被我们省掉了,但是这些状态可能会被第K大的取到,所以我们要先办法保留状态。

我们这里用三个数组,cnt1,cnt2和用来DP的数组D。

cnt1[k]表示取第i件物品时,第k大的价值。

cnt2[k]表示不取第i件物品时,第k大的价值。

D[j][k]表示背包容量为j时,第k大的价值。

我们可以看到,在第i,j个状态时,我们可以用在i-1状态时的D数组推得cnt1,和cnt2。再用cnt1,2来推当前的D数组。写出来是这样的:

cnt1[k]=d[j-v[i]][k]+c[i];

cnt2[k]=d[j][k];

D=cnt1和cnt2的合并。

到这里,我们发现其实这里就是一个单纯的递推了,我们从上个状态推到当前状态,然后继续推下一个,直到推到D[V][K]。

注意在合并的时候注意判重(我这里的判重是采用的别人的代码...)。

#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>using namespace std;int N,V,K,T,cnt1[35],cnt2[35],c[105],v[105];int d[1005][35];int main(){    scanf("%d",&T);    while (T--)    {        memset(d,0,sizeof(d));        memset(cnt1,0,sizeof(cnt1));        memset(cnt2,0,sizeof(cnt2));        scanf("%d%d%d",&N,&V,&K);        for (int i=1;i<=N;i++) scanf("%d",&c[i]);        for (int i=1;i<=N;i++) scanf("%d",&v[i]);        for (int i=1;i<=N;i++)            for (int j=V;j>=v[i];j--)        {            for (int k=1;k<=K;k++)            {                cnt1[k]=d[j-v[i]][k]+c[i];                cnt2[k]=d[j][k];            }            int t1=1,t2=1,t3=1;            while (t3<=K && (t1<=K || t2<=K) )            {                if (cnt1[t1]>cnt2[t2]) d[j][t3]=cnt1[t1++];                else d[j][t3]=cnt2[t2++];                if (d[j][t3]!=d[j][t3-1]) t3++;            }        }        printf("%d\n",d[V][K]);    }    return 0;}

0 0
原创粉丝点击