码迷,mamicode.com
首页 > 其他好文 > 详细

hihocoder 1320 压缩字符串(字符串+dp)

时间:2017-08-16 19:10:38      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:ems   ret   memset   tin   字符串   har   循环   int   搜索   

题解:

其实就是对应三种dp的转移方式

1、拼接类型

dp[i][j] = dp[i][c] + dp[c][j]

2、不变类型

dp[i][j] = j-i+1

3、重复类型(必须满足有k个循环节)

dp[i][j] = width(k) + 2 + dp[i][i+L-1]

 

直接记忆化搜索即可,复杂度n^3logn(枚举循环节近似为logn)

 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char S[110];
int dp[110][110];

int width(int x){
    int l = 0;
    while(x) { l++; x /= 10; }
    return l;
}

int dfs(int i, int j){
    if(i > j) return 0;
    if(dp[i][j] < 100) return dp[i][j];
    int L = j-i+1;
    if(L == 1) return 1;
    dp[i][j] = L;
    for(int c = i; c < j; c++) dp[i][j] = min(dp[i][j], dfs(i, c) + dfs(c+1, j));
    for(int k = 2; k <= L; k++){
        if(L % k != 0) continue;
        int l = L/k, f = 0;
        for(int t = 0; t < k-1 && !f; t++){
            for(int c = 0; c < l && !f; c++)
                if(S[i+l*t+c] != S[i+l*(t+1)+c]) f = 1;
        }
        if(!f) dp[i][j] = min(dp[i][j], width(k)+2+dfs(i, i+l-1));
    }
    return dp[i][j];
}

int main()
{
    int T;
    cin>>T;
    while(T--){
        cin>>S;
        int n = strlen(S);
        memset(dp, 1, sizeof(dp));
        cout<<dfs(0, n-1)<<endl;
    }
    return 0;
}

 

hihocoder 1320 压缩字符串(字符串+dp)

标签:ems   ret   memset   tin   字符串   har   循环   int   搜索   

原文地址:http://www.cnblogs.com/Saurus/p/7374744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!