Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %llu
System Crawler (2015-08-21)
Description
Run Length Encoding(RLE) is a simple form of compression. RLE consists of the process for searching for a repeated runs of a single character in a string to be compressed, and replacing them by a single instance of the character and a run count. For example, a stringabcccddddddefgggggggggghijk is encoded into a string ab3c6def10ghijk by RLE.
A new compression method similar to RLE is devised and the rule of the method is as follows: if a substring S<tex2html_verbatim_mark> is repeated k<tex2html_verbatim_mark> times, replace k<tex2html_verbatim_mark> copies of S<tex2html_verbatim_mark> by k(S)<tex2html_verbatim_mark> . For example, letsgogogo is compressed into lets3(go). The length of letsgogogo is 10, and the length of lets3(go) is 9. In general, the length of k(S)<tex2html_verbatim_mark> is (number of digits in k<tex2html_verbatim_mark> ) + (length of S<tex2html_verbatim_mark> ) + 2 (for `(' and `)'). For example, the length of 123(abc) is 8. It is also possible to nest compression, so the substring S<tex2html_verbatim_mark> may itself be a compressed string. For example,nowletsgogogoletsgogogo could be compressed as a now2(lets3(go)), and nowletsgogogoletsgogogoandrunrunrun could be compressed as now2(lets3(go))and3(run).
Write a program that, for a given string, gives a shortest compressed string using the compression rules as described above.
Input
Your program is to read from standard input. The input consists of T<tex2html_verbatim_mark> test cases. The number of test cases T<tex2html_verbatim_mark> is given in the first line of the input. Each test case consists of a single line containing one string of no more than 200 characters drawn from a lower case alphabet. The length of shortest input string is 1.
Output
Your program is to write to standard output. Print exactly one line for each test case. For each test case, print the length of the shortest compressed string.
The following shows sample input and output for four test cases.
Sample Input
4
ababcd
letsgogogo
nowletsgogogoletsgogogo
nowletsgogogoletsgogogoandrunrunrun
Sample Output
6
9
15
24
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std; char s[];
int dp[][]; int check(int l,int r,int k)
{
int i,j;
if(l>r)
return ;
for(i=l;i<=r;i++)
{
for(j=;i+j*k<=r;j++)
{
if(s[i]!=s[i+j*k])
return ;
}
}
return ;
} int digit(int a)
{
int s=;
while(a)
{
s++;
a=a/;
}
return s;
} int main()
{
int T;
int i,j,k,p,len;
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
len=strlen(s);
for(i=;i<len;i++)
{
for(j=;j<len;j++)
{
dp[i][j]=;
}
}
for(i=;i<len;i++)
dp[i][i]=;
for(i=;i<=len;i++)
{
for(j=;j+i-<len;j++)
{
int b=j,e=j+i-;
for(k=b;k<e;k++)
{
dp[b][e]=min(dp[b][e],dp[b][k]+dp[k+][e]);
}
for(p=;p<=i/;p++)
{
if(i%p==)
{
if(check(b,e,p))
{
dp[b][e]=min(dp[b][e],digit(i/p)++dp[b][b+p-]);
}
}
}
}
}
printf("%d\n",dp[][len-]);
}
return ;
}