Bone Collector II
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.
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.
題意:T組數據,N個骨頭,揹包容量爲V,求第K優解
第二行爲價值,第三行爲體積
分析:dp[i][j]表示體積爲i時第j優解
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int V,K;
int a[35],b[35],dp[1005][35];
int c[105],w[105],d[70];
int cmp(int a1,int b1)
{
return a1>b1;
}
void solve(int c1,int w1)
{
int i,l,j;
for(i=V;i>=c1;i--)
{
for(j=1;j<=K;j++)
{
a[j]=dp[i][j]; //a[]用來存不放當前物品各個體積狀態下的價值
b[j]=dp[i-c1][j]+w1; //b[]用來存放當前物品各個體積狀態下的價值
d[j-1]=a[j];
}
//選取a和b數組當中的前k大,用來更新dp數組,表示體積爲i時的第j優解
for(j=1;j<=K;j++)
{
d[j+K-1]=b[j];
}
sort(d,d+2*K,cmp);
int temp=d[0];
dp[i][1]=temp;
l=2;
for(j=1;j<2*K;j++)
{
if(d[j]!=temp)
{
dp[i][l++]=d[j];
temp=d[j];
}
if(l==K+1)
break;
}
}
}
int main()
{
int T,n,i,j;
scanf("%d",&T);
while(T--)
{
memset(d,0,sizeof(d));
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(dp,0,sizeof(dp));
scanf("%d%d%d",&n,&V,&K);
for(i=0;i<n;i++)
scanf("%d",&w[i]);
for(i=0;i<n;i++)
scanf("%d",&c[i]);
for(i=0;i<n;i++)
{
solve(c[i],w[i]);
}
printf("%d\n",dp[V][K]);
}
return 0;
}