luogu P1858 多人背包

嘟嘟嘟


既然让求前\(k\)优解,那么就多加一维,\(dp[j][k]\)表示体积为\(j\)的第\(k\)优解是啥(\(i\)一维已经优化掉了)。
考虑原来的转移方程:dp[j] = max(dp[j], dp[j - c[i]] + v[i])。
现在多了一维,那么dp‘[j][k]就分别从dp[j][]和dp[j - c[i]][]中取前\(k\)大的即可。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxm = 5e3 + 5;
const int maxk = 55;
const int maxn = 205;
inline ll read()
{
	ll ans = 0;
	char ch = getchar(), last = ' ';
	while(!isdigit(ch)) last = ch, ch = getchar();
	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
	if(last == '-') ans = -ans;
	return ans;
}
inline void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}

int n, m, K, c[maxn], v[maxn];
int dp[maxm][maxk];

int main()
{
	K = read(); m = read(); n = read();
	for(int i = 1; i <= n; ++i) c[i] = read(), v[i] = read();
	Mem(dp, 128); dp[0][1] = 0;
 	for(int i = 1; i <= n; ++i)
 		for(int j = m; j >= c[i]; --j)
 		{
            int t1 = 1, t2 = 1, len = 0;
            static int tp[maxk];
            while(len < K)
			{
        		if(dp[j][t1] > dp[j - c[i]][t2] + v[i]) tp[++len] = dp[j][t1++];
                else tp[++len] = dp[j - c[i]][t2++] + v[i];
            }
            for(int k = 1; k <= K; ++k) dp[j][k] = tp[k];
        }
    int ans = 0;
    for(int i = 1; i <= K; ++i) ans += dp[m][i];
	write(ans), enter;
}
posted @ 2019-01-21 15:13  mrclr  阅读(117)  评论(0编辑  收藏  举报