POJ 2176 Folding

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值