UVa 1630 串折叠(记忆化搜索)
UVA - 1630
Description ![]() Bill is trying to compactly represent sequences of capital alphabetic characters from `A' to `Z' by folding repeating subsequences inside them. For example, one way to represent a sequence `AAAAAAAAAABABABCCD' is `10(A)2(BA)B2(C)D'. He formally defines folded sequences of characters along with the unfolding transformation for them in the following way:
According to this definition it is easy to unfold any given folded sequence. However, Bill is much more interested in the reverse transformation. He wants to fold the given sequence in such a way that the resulting folded sequence contains the least possible number of characters. InputInput file contains several test cases, one per line. Each of them contains a single line of characters from `A' to `Z' with at least 1 and at most 100 characters. OutputFor each input case write a different output line. This must be a single line that contains the shortest possible folded sequence that unfolds to the sequence that is given in the input file. If there are many such sequences then write any one of them. Sample InputAAAAAAAAAABABABCCD NEERCYESYESYESNEERCYESYESYES Sample Output9(A)3(AB)CCD 2(NEERC3(YES)) |
分析:求最短的串,可以明显看出该问题具有最优子结构,动态规划自是不必说,问题的关键在于如何保存和处理那些重复的子串。dp[i][j]代表从字符串的i下标开始一直到j下标结束的压缩后的最短串长度,那么状态转移方程为dp[i][j]=min{dp[i][j],dp[i][k]+dp[k+1][j]},可以用记忆化搜索。先开一个二维string数组,用来保存原串的所有子串,然后在搜索过程中,不断的压缩字符串,同时判断一下重复的次数一起保存到字符串中,递归求解。其他的代码注释给的很详细。
时间:2016/7/21
AC代码:
#include<iostream>
#include<cstdio>
#include<sstream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#define INF 1<<29
#define eps 1e-9
#define LD long double
#define LL long long
const int maxn = 100 + 10;
using namespace std;
int dp[maxn][maxn];//str的i下标开始一直到j下标结束的压缩后的最短串长度
string sub[maxn][maxn];//保存str所有子串
string str;
int fold(int l, int r)
{
//枚举法判断重复的长度,不重复返回0
for (int i = 1; i <= (r - l + 1) / 2;i++)//枚举长度
{
int flag = 1;
if ((r-l+1)%i) continue;//剪枝
for (int j = l; j +i<= r; j++)
{
if (str[j] != str[j + i])
{
flag = 0;
break;
}
}
if (flag) return i;
}
return 0;
}
int dfs(int l, int r)
{
int & ans = dp[l][r];//引用
if (ans != -1) return ans;
if (l == r)
{
sub[l][r] = str[l];
return ans = 1;
}
ans = 1;
int res = INF,k;
for (int i = l; i < r; ++i)
{
int temp1 = dfs(l, i) + dfs(i + 1, r);//状态转移
if (temp1 < res)
{
k = i;
res = temp1;
}
}
sub[l][r] = sub[l][k] + sub[k + 1][r];
int len= fold(l, r);
if (len)
{
int rep = (r - l + 1) / len;
stringstream ss;//类似toString()方法
ss<< rep;
string t=ss.str();
string newstr = t + string("(") + sub[l][l + len-1] + string(")");
int temp2 = newstr.size();
if (temp2 < res)
{
res = temp2;
sub[l][r] = newstr;
}
}
return ans = res;
}
int main()
{
#ifdef LOCAL
freopen("data.txt", "r", stdin);
#endif
while (cin >> str)
{
memset(dp, -1, sizeof(dp));
int right = str.size() - 1;
dfs(0, right);
cout << sub[0][right] << endl;
}
return 0;
}