求两字符串相同最小刷次数(双重dp难)

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
题意:
就是有个刷区间东西,给出两个串s1和s2,一次只能将一个区间刷一次,问最少几次能让s1=s2。
列举题目两个例子区间刷的过程。
先将0~10刷一次,变成aaaaaaaaaaa
1~9刷一次,abbbbbbbbba
2~8:abcccccccba
3~7:abcdddddcba
4~6:abcdeeedcab
5:abcdefedcab
这样就6次,变成了s2串了
第二个样例也一样
0
先将0~10刷一次,变成ccccccccccb
1~9刷一次,cdddddddddcb
2~8:cdcccccccdcb
3~7:cdcdddddcdcb
4~6:cdcdcccdcdcb
5:cdcdcdcdcdcb
最后竟串尾未处理的刷一次
就变成了串2cdcdcdcdcdcd
所以一共7次
题解:
dp[i][j]表示i-j区间内的最少喷刷次数
对目标串我们先假设第i个字符的位置需要喷刷一次,对于所有位置都喷刷一次dp[i][j]=dp[i+1][j]+1、
在i-j区间内,如果有第k个跟第i个相同,利用k将i到j区间分成两部分dp[i][j]=min(dp[i+1][k]+dp[k+1][j]);
原本的字符串究竟需要喷刷多少次,用ans[i]记录0-i区间第二个字符串得出的喷刷次数,如果原字符串的i位置与目标字符串的i位置相同,那么这个位置就不用喷刷了,ans[i]=ans[i-1],如果不相同,就要就要借助一个位于o-i区间内的变量k来分割区间。
代码:
#include<stdio.h>
#include
#include<string.h>
#include
using namespace std;
char s1[105],s2[105];
int dp[105][105];
int ans[105],len;
int main()
{
while(cin>>s1>>s2)
{
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++)
{
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[i]=dp[0][i];
for(int i=0;i<len;i++)
{
if(s1[i]==s2[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;
}

发布了23 篇原创文章 · 获赞 0 · 访问量 321

猜你喜欢

转载自blog.csdn.net/qq_45762392/article/details/105499005