// 第K大背包問題
// 這好比從一個年級中選擇成績前10名的同學
// 則最少要知道每個班中的前10名同學的成績
// 對於每個狀態增加以維,表示當前的第K大
// 因為對於狀態轉移方程,dp[j] = max(dp[j], dp[j][j-v[i]]+w[i])
// 最大值要麼是dp[j], dp[j][j-v[i]]+w[i],之一,另外一個呢,可能是
// 第2大,第3大...
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXK 31
#define MAXN 101
#define MAXV 1001
#define INF 0x3f3f3f3f
int v[MAXN], w[MAXN], dp[MAXV][MAXK], ans[MAXK+MAXK], pos, t_pos;
int zero_one_knapsack(int n, int max_v, int k)
{
memset(dp, 0, sizeof(dp));
for(int i = 0; i < n; i ++) {
for(int j = max_v; j >= v[i]; j --) {
pos = 0; t_pos = 0;
for(int t = 0; t < k; t ++) {
ans[pos ++] = dp[j][t];
ans[pos ++] = dp[j-v[i]][t]+w[i];
}
sort(ans, ans+pos);
dp[j][t_pos ++] = ans[pos-1];
for(int t = pos-2; t >= 0; t --) {
if( t_pos > k || ans[t] == ans[t+1] ) {
continue;
}
dp[j][t_pos ++] = ans[t];
}
}
}
return dp[max_v][k-1];
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int n, max_v, k, cas;
scanf("%d", &cas);
while( cas -- ) {
scanf("%d %d %d", &n, &max_v, &k);
for(int i= 0; i < n; i ++) {
scanf("%d", &w[i]);
}
for(int i = 0; i < n; i ++) {
scanf("%d", &v[i]);
}
printf("%d\n", zero_one_knapsack(n, max_v, k));
}
return 0;
}
hdu_2639
最新推荐文章于 2020-07-22 11:07:58 发布