# HDU 2476：String painter （区间DP）

### 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

### AC代码

#include <iostream>
#include<cstdio>
using namespace std;
#include<algorithm>
#include<string.h>
char s1[105],s2[105];
int dp[105][105],ans[105];
//dp[i][j]表示从i到j的最小次数
int main()
{
while(gets(s1))
{
gets(s2);
int len=strlen(s1);
memset(dp,0,sizeof(dp));
for(int j=0; j<len; j++)
for(int i=j; i>=0; i--)
{
dp[i][j]=dp[i+1][j]+1;  //先假设无优化刷当前区间
for(int k=i+1; k<=j; k++)   //用k来分割区间
if(s2[i]==s2[k])    //找到相等位置，更新最小次数
dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);
}
for(int i=0; i<len; i++)    //初始化ans
ans[i]=dp[0][i];
for(int i=0; i<len; i++)
{
if(s1[i]!=s2[i])    //分割区间找最优解
for(int j=0; j<i; j++)
ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
else ans[i]=ans[i-1];   //如果相等，当前位置可以不刷
}
printf("%d\n",ans[len-1]);
}
return 0;
}

### 2 只已被捕捉

• 656 Chrome | 91.0.4472.77 Windows 10/11

还可以

• 千千 Edge | 91.0.864.37 Windows 10/11

哈哈，欢迎常来哦~