您的位置:首页 > 大数据 > 人工智能

HDU-2476-String painter【区间DP】

2017-03-23 13:42 537 查看
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

题目链接:hdu-2476

题目大意:每次能将一个区间里面的字母改成一个同一个字母,问最少需要多少次将a串变成b串

题目思路:看了题解,感觉很巧妙啊。

先计算出由空串变成b串的最小次数,然后处理a串

参考博客:here

以下是代码:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#include <deque>
#include <list>

using namespace std;
int dp[200][200];
int ans[200];
int main()
{
string a,b;
while(cin >> a >> b)
{
//初始化
int len = b.size();
for(int i = 0; i < len; i++)
{
for (int j = i; j < len; j++)
{
dp[i][j] = j - i + 1;
}
}
//将空串换成b串
for (int i = len - 2; i >= 0; i--)
{
for (int j = i; j < len; j++)
{
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]);//寻找I-K最佳方案
}
}

}
}
//a串初始
for (int i = 0; i < len; i++) ans[i] = dp[0][i];

for(int i = 0; i < len; i++)
{
if (a[i] == b[i])
{
if (i == 0) ans[i] = 0;
else ans[i] = ans[i - 1];  //如果对应位置相等这个位置可以不刷
}
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp hdu