[LGOJ2340]奶牛会展——[简单DP]

[LGOJ2340]奶牛会展——[简单DP]_第1张图片
【题意分析】

把智商看成费用,情商看成价值,就是一道水背包

至于数组下标会有负数,只要都加上一个值使下标为正即可

最后的答案要遍历所有状态

Code:

#include 
#include 
#include 
#include 
#include 
#include 
#define lim 400000
#define MAXN 900000
#define INF 2147400000
using namespace std;

int iq[MAXN], eq[MAXN], dp[MAXN], n, ans = -INF;

inline int read () {
	register int s = 0, w = 1;
	register char ch = getchar ();
	while (! isdigit (ch)) {if (ch == '-') w = -1; ch = getchar ();}
	while (isdigit (ch)) {s = (s << 3) + (s << 1) + (ch ^ 48); ch = getchar ();}
	return s * w;
}

int main () {
	n = read ();
	for (register int i = 1; i <= n; i++) iq[i] = read (), eq[i] = read ();
	for (register int i = 0; i <= MAXN - 1; i++) dp[i] = -INF;
	dp[lim] = 0;
	for (register int i = 1; i <= n; i++)
		if (iq[i] > 0) for (register int j = lim * 2; j >= iq[i]; j--)
			dp[j] = max (dp[j], dp[j - iq[i]] + eq[i]);
		else for (register int j = 0; j <= lim * 2 + iq[i]; j++)
			dp[j] = max (dp[j], dp[j - iq[i]] + eq[i]);
	for (register int i = lim; i <= lim * 2; i++)
		if (dp[i] >= 0) ans = max (ans, dp[i] + i - lim);
	return printf ("%d\n", ans), 0;
}

你可能感兴趣的:(动态规划)