Some cows have certain values of s and f, which have positive and negative values. Finally, let us ensure the sum of s and f is not negative, the maximum value of s + f.
Idea: we can set dp [I] [s] to the maximum value of f when the s Value of the former I head ox is s, which turns into a backpack problem, consider s as a volume, f as a value, and successfully convert two dimensions into one dimension. Because there is a negative number, we can add a value and convert all to a positive number. When dealing with negative numbers, the cyclical order needs to be changed. One is the 01 backpack and the other is the full backpack. That is, a reverse loop, a positive loop, and finally the maximum value.
Code:
[Cpp]
// 2184
# Include <iostream>
# Include <cstdio>
# Include <string. h>
# Include <climits>
Using namespace std;
# Define CLR (arr, val) memset (arr, val, sizeof (arr ))
Const int n= 110;
Const int M = 100005;
Struct cow {
Int s, f;
} Cc [N];
Int dp [2 * M];
Int max (int a, int B ){
Return a> B? A: B;
}
Int main (){
// Freopen ("1.txt"," r ", stdin );
Int n;
While (scanf ("% d", & n )! = EOF ){
For (int I = 0; I <n; ++ I ){
Scanf ("% d", & cc [I]. s, & cc [I]. f );
}
For (int I = 0; I <2 * M; ++ I)
Dp [I] = INT_MIN;
Dp [100000] = 0;
For (int I = 0; I <n; ++ I ){
If (cc [I]. s> = 0 ){
For (int j = 2 * M-1; j> = cc [I]. s; -- j ){
If (dp [j-cc [I]. s]> INT_MIN)
Dp [j] = max (dp [j], dp [j-cc [I]. s] + cc [I]. f );
}
}
Else {
For (int j = cc [I]. s; j-cc [I]. s <2 * M; ++ j ){
If (dp [j-cc [I]. s]> INT_MIN)
Dp [j] = max (dp [j], dp [j-cc [I]. s] + cc [I]. f );
}
}
}
Int ans = INT_MIN;
For (int I = 100000; I <2 * M; ++ I ){
If (dp [I]> = 0)
Ans = max (ans, dp [I] + I-100000 );
}
Printf ("% d \ n", ans );
}
Return 0;
}
Author: wmn_wmn