String painter
Time Limit:3000MS Memory Limit:0KB 64bit
IO Format:%lld & %llu
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.
Output
A single line contains one integer representing the answer.
Sample Input
zzzzzfzzzzz abcdefedcba abababababab cdcdcdcdcdcd
Sample Output
6 7
题意:给定两个长度相等的字符串,记为 A, B, 均只包含小写字母。每次可以把一个连续字串 “刷” 成相同的一个字母,问至少需要几次才能够把 A 变为 B。
思路:
假设一个空串要刷成目标串的极端情况(题意保证不存在空串,可以假设为所有字母均与目标串不同)。
用 dp[ i ][ j ] 表示把 A 串的 i-j 区间刷成目标串 B 的 i-j 所需要的最少步数,首先初始化所有的 dp[ i ][ i ] 为 1 。
dp[ i ][ j ] = dp[ i+1 ][ j ] + (strB[ i ] == strB[ j ]?0:1); 如果strB[ i ] == strB[ j ],则 i,j 这两个位置可以同时刷。
同理,对于k=(i+1...j )如果str[k]==str[i] , 则dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]),,因为刷i的时候可以与k同时刷。
上面是对初始串与目标串完全不同的情况。
如果有部分的不同:
ans[ i ] 表示将 strA[ 1...i ] 刷成 strB [ 1...i ]的最小步数,
if strA[i]==strB[i], f[ i ] = f[ i-1 ];
else f[ i ] = min( f[ i ], f [ j ]+dp[ j+1 ][ i ]) ,1 <= j <= i-1
<span style="font-size:18px;">#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <string> #include <algorithm> #include <queue> #include <stack> using namespace std; const double PI = acos(-1.0); const double e = 2.718281828459; const double eps = 1e-8; const int MAXN = 110; int dp[MAXN][MAXN]; int f[MAXN]; char strA[MAXN], strB[MAXN]; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n; while(scanf("%s %s", strA+1, strB+1) != EOF) { n = strlen(strA+1); for(int i = 0; i <= n; i++) dp[i][i] = 1; for(int len = 2; len <= n; len++) { // 枚举区间长度 for(int i = 1, j = len; j <= n; i++, j++) { dp[i][j] = dp[i+1][j]+(strB[i]==strB[j]?0:1); for(int k = i+1; k <= j-1; k++) { if(strB[i] == strB[k]) dp[i][j] = min(dp[i][j], dp[i+1][k]+dp[k+1][j]); } } } for(int i = 1; i <= n; i++) { f[i] = dp[1][i]; } if(strA[1] == strB[1]) f[1] = 0; for(int i = 1; i <= n; i++) { if(strA[i] == strB[i]) f[i] = f[i-1]; else { for(int j = 1; j <= i-1; j++) { f[i] = min(f[i], f[j]+dp[j+1][i]); } } } cout<<f[n]<<endl; } return 0; }</span>