1365: Pku2184 Cow exhibition
Description
Her cow Bessie N selected from a number of dairy cows at an exhibit, she has been given two indexes each cow, Si and Fi (-1000 <= Si, Fi <= 1000), representing each head cows smart index and happiness index. Of course, she hoped that the selection of cows Si Fi and the sum of the maximum, and in order to show her cows comprehensive development, and Si Fi respective sum not less than 0.
Input
Line 1: Number of cows N, N <= 100
2 to N + 1 line: each cow Si and Fi
Si (-1000 <= Si <= 1000)
Fi (-1000 <= Fi <= 1000)
2 to N + 1 line: each cow Si and Fi
Si (-1000 <= Si <= 1000)
Fi (-1000 <= Fi <= 1000)
Output
The maximum sum of qualified and Fi-Si
Sample Input
5
-5 7
8 -6
6 -3
2 1
-8 -5
Sample Output
8
This question is a variation of the question a more classic 01 backpack
Dominos This question is also a similar problem,
you can also do a search. The favorable value added all at the same time make a note of the possible elements of non-compliance, to make a rule out, find the correct optimal value.
Sometimes knapsack (partial stack) can be used to do random greedy, more general idea from a random pile into the pile less.
This question is a pit so most places
To initialize the array f assigned -0x3fffffff (in fact -200,000 enough) and the f [1000000] = 0 degrees can occur because humor
negative number.
See Code
#include<bits/stdc++.h> using namespace std; const int INF=0x3f3f3f3f; int dp[200001]; int value[101]; int weight[101]; int n; int main() { int k=100000; while(~scanf("%d",&n)) { for(int i=0;i<n;i++) { scanf("%d%d",&value[i],&weight[i]); } for(int i=0;i<=200000;i++)dp[i]=-INF; dp[k]=0; for(int i=0;i<n;i++) { if(value[i]>0) { for(int j=200000;j>=value[i];j--) if(dp[j-value[i]]>-INF) dp[j]=max(dp[j],dp[j-value[i]]+weight[i]); } else { for(int j=0;j<=200000+value[i];j++) if(dp[j-value[i]]>-INF) dp[j]=max(dp[j],dp[j-value[i]]+weight[i]); } } int ans=0; for(int i=100000;i<=200000;i++) if(dp[i]>=0&&dp[i]+i-100000>ans) ans=dp[i]+i-100000; printf("%d\n",ans); } return 0; }