题目大意:
就是给出一个长度不超过5000的字符串进行压缩
S = S1(d1) + S2(d2) + ... + Sk(dk)
Si是字串, di表示这个字串连续出现的次数
要使得Si的总长度最小
大致思路:
很明显可以用DP来做
思路和Gym 100337B 类似, 先处理出以 i 位置和 j 位置作为结尾向前能匹配的最大长度dp[i][j]
然后枚举循环节的长度即可
总体复杂度O(n*n*logn)
代码如下:
Result : Accepted Memory : 49368 KB Time : 342 ms
/*
* Author: Gatevin
* Created Time: 2015/9/4 12:53:50
* File Name: fz.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;
char s[5050];
short dp[5010][5010];
int mi[5010];
const int inf = 1e9 + 7;
int vis[5010];
int clen[5010];
stack<pair<int, int> > S;
#define mp make_pair
int main()
{
freopen("decomp.in", "r", stdin);
freopen("decomp.out", "w", stdout);
scanf("%s", s + 1);
int len = strlen(s + 1);
for(int i = 1; i <= len; i++)
for(int j = 1; j <= len; j++)
if(s[i] == s[j]) dp[i][j] = dp[i - 1][j - 1] + 1;
for(int i = 1; i <= len; i++)
{
mi[i] = i;
vis[i] = i - 1;
clen[i] = 1;
for(int L = 1; L <= i; L++)
{
int ti = i;
while(ti - L >= 0)
{
if(dp[i][ti] >= L)
{
if(mi[i] > mi[ti - L] + L)
{
mi[i] = mi[ti - L] + L;
vis[i] = ti - L;
clen[i] = L;
}
//mi[i] = min(mi[i], mi[ti - L] + L);
ti -= L;
}
else break;
}
}
}
printf("%d\n", mi[len]);
int now = len;
S.push(mp(len, 0));
while(now >= 1)
{
S.push(mp(vis[now], clen[now]));
now = vis[now];
}
while(!S.empty())
{
int start = S.top().first;
int l = S.top().second;
S.pop();
if(start == len) break;
for(int i = start + 1; i <= start + l; i++)
printf("%c", s[i]);
int end = S.top().first;
printf(" %d\n", (end - start)/l);
}
return 0;
}