每个牛有两个属性 幽默值和风趣值,有可能为负值,从 n个牛中挑选一些牛,使这些牛在风趣值相加>=0并且幽默值相加>=0的条件下幽默值和风趣值相加最大;
如果 没负数,则是个裸的01背包,但有负数就得另加处理,也算是个技巧吧,加上个大值使其变为正,这个大值必须要满足当全是负时加上这个大值也会>=0;详细的就理解代码吧,
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
const int maxn=2e5+10000;
int dp[maxn];
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int a,b,n;
while (cin>>n)
{
memset(dp,-0x3f3f3f3f,sizeof(dp));
dp[10000]=0;
for (int i=1;i<=n;i++)
{
cin>>a>>b;
if (a>0)
{
for (int j=maxn-1;j>=a;j--)
dp[j]=max(dp[j],dp[j-a]+b);
}
else //如果小于零,就直接这样处理,从小到大枚举,保证其没有后效性;
{
for (int j=0;j<maxn+a;j++)
dp[j]=max(dp[j],dp[j-a]+b);
}
}
int ans=0;
for (int i=10000;i<maxn;i++)
{
if (dp[i]>0)
ans=max(ans,dp[i]+i-10000);
}
cout<<ans<<endl;
}
return 0;
}