uva 1630 KMP判断周期串 和 区间DP 压缩字符串

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
string dp[160][160];
char s[160],t[160];
int f[160];
string ToString(int x){
	string res = "";
	while(x){
		res += (char)('0' + (x % 10));
		x /= 10;
	}
	reverse(res.begin(),res.end());
	return res;
}
void GetFail(char *s){
	int len = strlen(s);
	f[0] = f[1] = 0;
	for(int i = 1;i < len;i++){
		int j = f[i];
		while(j && s[i] != s[j]) j = f[j];
		f[i+1] = s[i] == s[j] ? j+1:0;
	}
}
int main(){
	while(scanf("%s",s) == 1){
		int len = strlen(s);
		for(int i = 0;i < len;i++)
		dp[i][i] = string("") + s[i];
		for(int l = 2;l <= len;l++){
			for(int i = 0;i + l - 1 < len;i++){
				int j = i + l - 1;
				dp[i][j]="";
				for(int k = i;k <= j;k++){
					dp[i][j] += s[k];
					t[k-i] = s[k];
				}
				t[j-i+1] = 0;
				GetFail(t);
				if(l % (l - f[l]) == 0){
					int n = l - f[l];
					string tt="";
					tt = ToString(l / n);
					tt += '(';
					tt += dp[i][i+n-1];
					tt += ')';
					if(tt.length() < dp[i][j].length()) dp[i][j] = tt;
				}
				for(int k = i;k < j;k++){
				if(dp[i][k].length() + dp[k+1][j].length() < dp[i][j].length()){
					dp[i][j] = dp[i][k] +dp[k+1][j];
				}
			}
			}
		}
		cout<<dp[0][len-1]<<endl;
	}
}

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/sky_zdk/article/details/78454056
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞