HDU 2639 Bone Collector II
0-1背包问题。求第K大的值。
http://acm.hdu.edu.cn/showproblem.php?pid=2639
这道题目第一次做的时候是一场自己挂的WEB-DIY中的一题,那时候是直接开了一个一维的dp[ j ]数组,用来记录获得价值j最大的体积,然后转化为简单的0-1背包,,思路感觉很简单,然后已提交,RE。伤了。后来才发现,最大价值可能要上亿。。。囧了。
恩,后来用一位数组来记录。
接着么。。。
#include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; typedef long long LL; #define MIN(a,b) (a > b ? b : a) int dp[1005][1005],c[1005],v[1005]; int a[1005],b[1005]; int main() { int T; scanf("%d",&T); while (T--) { int N,V,K; memset(dp,0,sizeof(dp)); scanf("%d%d%d",&N,&V,&K); for (int i=0;i<N;i++) scanf("%d",&v[i]); for (int i=0;i<N;i++) scanf("%d",&c[i]); for (int i=0;i<N;i++) { for (int j=V;j>=c[i];j--) { for (int p=1;p<=K;p++) { a[p] = dp[j-c[i]][p] + v[i]; b[p] = dp[j][p]; } int t1,t2,t3; t1 = t2 = t3 = 1; a[K+1] = b[K+1] = -1; while (t1 <= K &&(t2 <= K || t3 <= K)) { if (a[t2] > b[t3])dp[j][t1] = a[t2++]; else dp[j][t1] = b[t3++]; if (dp[j][t1] != dp[j][t1-1])t1++; } } } printf("%d\n",dp[V][K]); } return 0; }