题目:
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
题解:
我们先预处理出一个f[i][j],表示一个空白的串i-j部分如果要涂成第二个串一样且i率先涂上相同颜色(可以连着涂··只要保证i先匹配上)需要的最少次数···然后再更新ans[i]即可··具体看代码
代码:
#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<ctime> #include<cctype> #include<cstring> #include<string> #include<algorithm> using namespace std; const int inf=0x3f3f3f3f; const int N=105; int n,f[N][N],ans[N]; char s[N],t[N]; int main() { // freopen("a.in","r",stdin); while(~scanf("%s%s",s+1,t+1)) { n=strlen(s+1); memset(f,inf,sizeof(f)); memset(ans,inf,sizeof(ans)); ans[0]=0; for(int i=1;i<=n;i++) f[i][i]=1; for(int i=1;i<n;i++) if(t[i]==t[i+1]) f[i][i+1]=1; else f[i][i+1]=2; for(int i=n-2;i>=1;i--) for(int j=i+2;j<=n;j++) { f[i][j]=f[i+1][j]+1; for(int k=i+1;k<=j;k++) if(t[i]==t[k]) f[i][j]=min(f[i][j],f[i+1][k-1]+f[k][j]);//在涂上位置时顺便涂上i位置 } for(int i=1;i<=n;i++) { if(s[i]==t[i]) ans[i]=ans[i-1]; //如果这个位置已经相等就不涂 else for(int j=0;j<i;j++) ans[i]=min(ans[i],ans[j]+f[j+1][i]); //否则找到最优解 } cout<<ans[n]<<endl; } return 0; }