这道题转移方程不太好想,table[i][j]表示从i到j压缩后最小的字符数,comp[i][mid][j]表示str[i~j]中从str[i]开始str[i~(mid-1)]的最长循环串次数-1,例如letsgogogo comp[5][7][10] = 2,
table[i][j] = min table(bit(comp[i][k][j])+2)+table[k+(k-i+1)*(comp[i][k][j]+1))][j])
table[i][k]+table[k+1][j]
(i <= k < j)
由于要计算comp[i][k][j],所以复杂度实际为O(n^4),所以要先把com[i][k][j]预处理出来,我想到的是先用O(n^3)计算出comp[i][k][j] =1的情况,再用O(n^3)递推出其他的情况,所以最后的复杂度为O(n^3)+O(n^3)+O(n^3)=O(n^3)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>
#include <map>
#include <string>
#include <climits>
#include <set>
#include <string>
#include <sstream>
#include <utility>
#include <ctime>
using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::make_pair;
using std::greater;
using std::endl;
const int MAXN(210);
int comp[MAXN][MAXN][MAXN];
int table[MAXN][MAXN];
char str[MAXN];
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%s", str+1);
int len = strlen(str+1);
memset(comp+1, 0, sizeof(comp[0])*len);
for(int i = 2; i <= len; ++i)
{
int l = i-1, r = i, tl = 1;
while(l >= 1 && r <= len)
{
if(memcmp(str+l, str+i, tl) == 0)
{
for(int j = 0; j < tl; ++j)
comp[l][i][r+j] = 1;
}
--l;
++r;
++tl;
}
}
for(int i = 2; i <= len; ++i)
{
for(int l = i-1; l >= 1; --l)
{
int temp = i-l;
if(comp[l][i][i+temp-1])
{
int count = 2;
for(int r = i+temp*2-1; r <= len; r+= temp, ++count)
{
if(!comp[r-temp+1-temp][r-temp+1][r])
break;
for(int k = 0; k < temp; ++k)
comp[l][i][r+k] = count;
}
}
}
}
for(int i = 1; i <= len; ++i)
table[i][i] = 1;
for(int l = 2; l <= len; ++l)
{
int tl1 = len-l+1;
for(int i = 1; i <= tl1; ++i)
{
int j = i+l-1;
int &cur = table[i][j];
cur = l;
for(int k = i; k < j; ++k)
{
int temp = table[i][k]+table[k+1][j];
int t1 = comp[i][k+1][j];
if(t1)
{
++t1;
temp = min(temp, (t1 >= 10? (t1 >= 100? 3: 2): 1)+table[i][k]+2+table[k+1+(t1-1)*(k-i+1)][j]);
}
cur = min(cur, temp);
}
}
}
printf("%d\n", table[1][len]);
}
return 0;
}