1. 程式人生 > >hihocoder 1320 壓縮字符串(字符串+dp)

hihocoder 1320 壓縮字符串(字符串+dp)

cst class ems using 記憶化搜索 string code logs strlen

題解:

其實就是對應三種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)