题目来源:
http://acm.hdu.edu.cn/showproblem.php?pid=2476
题目描述:
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.
Output
A single line contains one integer representing the answer.
Sample Input
zzzzzfzzzzz abcdefedcba abababababab cdcdcdcdcdcd
Sample Output
6 7
Source
Recommend
lcy
解题思路:
题目大意就是给你两个串,一次操作可以将a串的一个区间变成相同的一个字符,问从a串到b串,最少需要多少次操作;
解题分为两步,先考虑从空串到b串最少需要多少次,设dp[i][j]为从i到j变成b串需要多少次,已知dp[i][i]=1;我们可以初始化dp[i ][j ]=dp[i+1][j]+1,如果s2【i】=s2【k】,dp[i][]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]),因为如果i位和k位相同那么从i到j就相当于i+1到j。
然后就是用一个数组ans[i]表示从1到i,s1到s2需要多少次,我们可以得出,ans[i]=min(dp[j][i]+ans[j],dp[1][i])当s1[i]==s2[i]时ans[i]=ans[i-1];
代码:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn=1e5+10;
string a,b;
int dp[110][110],ans[110];
int main()
{
while(cin>>a>>b)
{
memset(dp,0,sizeof(dp));
int len=a.length();
for(int i=0;i<len;i++)dp[i][i]=1;
for(int l=2;l<=len;l++)
for(int i=0;i<=len-l;i++)
{
int j=l+i-1;
dp[i][j]=dp[i+1][j]+1;
for(int k=i+1;k<=j;k++)
if(b[i]==b[k])dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);
}
for(int i=0;i<len;i++)ans[i]=dp[0][i];
for(int i=0;i<len;i++)
{
if(a[i]==b[i])ans[i]=ans[i-1];
else
for(int j=0;j<i;j++)
ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
}
cout<<ans[len-1]<<endl;
}
return 0;
}