Bone Collector II_第k大背包

Time Limit : 5000/2000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 14   Accepted Submission(s) : 13

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

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

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

第k大的背包问题,用a,b两个数组记录加不加该物品下的背包价值,在通过两数组的比较,赋值给dp,dp增加一维记录第几大

#include<iostream>
#include<cstring>
using namespace std;
const int N=1050;
int dp[N][N],a[N],b[N];
int val[N],vol[N];
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,v,k;
        cin>>n>>v>>k;
        for(int i=1; i<=n; i++)
            cin>>val[i];
        for(int i=1; i<=n; i++)
            cin>>vol[i];
        memset(dp,0,sizeof(dp));
        for(int i=1; i<=n; i++)
            for(int j=v; j>=vol[i]; j--)
            {
                for(int h=1; h<=k; h++)
                {
                    a[h]=dp[j-vol[i]][h]+val[i];//数组a记录放该物品的第k大价值
                    b[h]=dp[j][h];//数组b记录不放该物体的第k大价值
                }
                a[k+1]=b[k+1]=-1;
                int x=1,y=1,z=1;
                while(z<=k&&(a[x]!=-1||b[y]!=-1))//a,b数组都还没超出k的情况下
                {
                    if(a[x]>b[y])//若是放的时候大,将a[x]的值给的dp,x加一;
                        dp[j][z]=a[x],x++;
                    else//否则,b的值给dp,y加一
                        dp[j][z]=b[y],y++;
                    if(dp[j][z]!=dp[j][z-1])//若前后两个数不是等大,z加一
                        z++;
                }
            }

            cout<<dp[v][k]<<endl;

    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/iwantstrong/p/5732408.html