01背包(变种)
http://acm.hdu.edu.cn/showproblem.php?pid=2476
String painter
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7666 Accepted Submission(s): 3738
Problem Description
There
are two strings A and B with equal length. Both strings are made up of
lower case letters. Now you have a powerful string painter. With the
help of the painter, you can change a segment of characters of a string
to any other character you want. That is, after using the painter, the
segment is made up of only one kind of character. Now your task is to
change A to B using string painter. What’s the minimum number of
operations?
Input
Input contains multiple cases. Each case consists of two lines:
The first line contains string A.
The second line contains string B.
The length of both strings will not be greater than 100.
The first line contains string A.
The second line contains string B.
The length of both strings will not be greater than 100.
Output
A single line contains one integer representing the answer.
Sample Input
zzzzzfzzzzz
abcdefedcba
abababababab
cdcdcdcdcdcd
Sample Output
6
7
Source
Recommend
lcy
题意:有n头牛,每一头牛有两个值,一个聪明值,一个幽默值。求所以牛两值之和的最大值,且其中聪明值之和和幽默值之和不能为负数
解法:可以发现此题问题就是01背包的取与不取的问题,但是这题背包容量会出现负数(负数不能作为数组下标)所以要将负数将为正数。
//#include <bits/stdc++.h> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <iostream> #include <algorithm> #include <iostream> #include <cstdio> #include <string> #include <cstring> #include <stdio.h> #include <queue> #include <stack>; #include <map> #include <set> #include <string.h> #include <vector> #define ME(x , y) memset(x , y , sizeof(x)) #define SF(n) scanf("%d" , &n) #define rep(i , n) for(int i = 0 ; i < n ; i ++) #define INF 0x3f3f3f3f #define mod 998244353 #define PI acos(-1) using namespace std; typedef long long ll ; int dp[200005]; int w[209] , val[209]; int main() { int n ; while(~scanf("%d" , &n)) { for(int i = 0 ; i <= 200000 ; i++) dp[i] = -INF ; dp[100000] = 0 ; for(int i = 1 ; i <= n ; i++) { scanf("%d%d" , &w[i] , &val[i]); } for(int i = 1 ; i <= n ; i++) { if(w[i] < 0 && val[i] < 0) continue ; if(w[i] > 0) { for(int j = 200000 ; j >= w[i] ; j--) { if(dp[j-w[i]] > -INF) dp[j] = max(dp[j] , dp[j-w[i]]+val[i]); } } else { for(int j = w[i] ; j <= 200000 + w[i] ; j++) { if(dp[j-w[i]] > -INF) dp[j] = max(dp[j] , dp[j-w[i]]+val[i]); } } } int ans = -INF ; for(int i = 100000 ; i <= 200000 ; i++) { if(dp[i] >= 0) { ans = max(ans , dp[i]+i-100000); } } cout << ans << endl; } return 0 ; }