C#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <string.h>
#include <set>
#include <map>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAXN = 100 + 10;
const int INF = 0x3f3f3f3f;
string str;
int dp[MAXN][MAXN];
string fold[MAXN][MAXN];
int Length(int l, int r)
{
for(int i=1;i<=(r-l+1)/2;i++)
{
if((r-l+1) % i)continue;
bool flag = true;
for(int j=l;j+i<=r;j++)
{
if(str[j] != str[j+i])
{
flag = false;
break;
}
}
if(flag) return i;
}
return 0;
}
int solve(int l, int r)
{
if(dp[l][r] != -1) return dp[l][r];
if(l == r)
{
dp[l][r] = 1;
fold[l][r] = str[l];
return dp[l][r];
}
int M = INF;
int p;
for(int i=l;i<r;i++)
{
int tmp = solve(l, i) + solve(i + 1, r);
if(tmp < M)
{
M = tmp;
p = i;
}
}
fold[l][r] = fold[l][p] + fold[p+1][r];
int len = Length(l, r);
if(len)
{
char t[10];
sprintf(t, "%d", (r - l + 1) / len);
string newstr = t + string("(") + fold[l][l+len-1] + string(")");
if(newstr.size() < M)
{
M = newstr.size();
fold[l][r] = newstr;
}
}
dp[l][r] = M;
return dp[l][r];
}
int main()
{
while(cin>>str)
{
int n = str.length();
memset(dp, -1, sizeof(dp));
solve(0, n - 1);
cout<<fold[0][n-1]<<endl;
}
return 0;
}
POJ 2176 Folding
最新推荐文章于 2019-11-27 20:56:58 发布