题解:
其实就是对应三种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; }