!!!!一定要注意排除掉a[i],b[i]全为负的情况
#include <iostream> using namespace std; #define INF 100005 #define NUM 101 #define MAX 200000 #define PLUS 100000 int a[NUM]; int b[NUM]; int dp[NUM][MAX]; int main() { int n; cin>>n; int suma=0,s=0,sumamin=0; int cur=0; for (int i=0;i<n;i++){ for (int j=0;j<MAX;j++){ dp[i][j]=-INF; } } for (int i=0;i<n;i++){ cin>>a[cur]>>b[cur]; if (a[cur]>0||b[cur]>0) { dp[cur][a[cur]+PLUS]=b[cur]; if (a[cur]>0){ suma+=a[cur]; }else{ sumamin+=a[cur]; } cur++; } } n=cur; suma+=PLUS; sumamin+=PLUS; if (a[0]>=0&&b[0]>=0){ s=max(s,a[0]+b[0]); } for (int i=1;i<n;i++) { for (int j=0;j<i;j++) { for (int k=sumamin;k<=suma;k++) { if (dp[j][k]!=-INF) { if (a[i]+k<0)continue; dp[i][k+a[i]]=max(dp[i][k+a[i]],dp[j][k]+b[i]); if (a[i]+k>=PLUS&&dp[i][k+a[i]]>=0) { s=max(s,k+a[i]-PLUS+dp[i][k+a[i]]); } } } } } cout<<s<<endl; return 0; }