典型的背包问题。设d(i,j)为前i头牛中聪明度总和为j时的幽默度最大值,则递推公式为d(i,j) = max{d(i - 1,j - si) + si, d(i - 1, j)},主要的问题是状态值存在负数,所以为了避免负数索引,加上一个偏移就行了。另外有些状态是无法达到的,就直接赋值为一个很小的负数,然后处理下就行。
#ifndef HEAD
#include <stdio.h>
#include <vector>
#include <math.h>
#include <string.h>
#include <string>
#include <iostream>
#include <queue>
#include <list>
#include <algorithm>
#include <stack>
#include <map>
using namespace std;
#endif // !HEAD
#ifndef QUADMEMSET
inline void QuadMemSet(void* dst, int iSize, int value)
{
iSize = iSize / 4;
int* newDst = (int*)dst;
#ifdef WIN32
__asm
{
mov edi, dst
mov ecx, iSize
mov eax, value
rep stosd
}
#else
for (int i = 0; i < iSize; i++)
{
newDst[i] = value;
}
#endif
}
#endif
int CH[2][200001];
#define LINF (-1000000000)
int GetValue(int i, int j)
{
if (j + 100000 < 0 || j + 100000 > 200000)
{
return LINF;
}
return CH[i][j + 100000];
}
void SetValue(int i, int j, int value)
{
CH[i][j + 100000] = value;
}
int main()
{
#ifdef _DEBUG
freopen("d:\\in.txt", "r", stdin);
#endif
int n;
scanf("%d\n", &n);
QuadMemSet(CH, sizeof(CH), LINF);
CH[0][100000] = 0;
int res = 0;
int minl =0;
int maxl = 0;
for (int i = 1; i <= n;i++)
{
int a, b;
scanf("%d %d\n", &a, &b);
if (a < 0)
minl += a;
else
maxl += a;
//QuadMemSet(CH[i & 1], sizeof(CH) / 2, LINF);
for (int j = minl; j <= maxl;j++)
{
int ij = GetValue((i - 1) & 1, j);
int jj = GetValue((i - 1) & 1, j - a);
if (jj != LINF)
{
jj += b;
}
SetValue(i & 1, j, std::max(ij, jj));
if (j >= 0 && std::max(ij,jj) >= 0)
{
res = res > (j + std::max(ij, jj)) ? res : (j + std::max(ij, jj));
}
}
}
printf("%d\n", res);
return 1;
}