题目大意:
折叠的定义如下:
- 一个字符串可以看成它自身的折叠。记作S = S
- X(S)是X(X>1)个S连接在一起的串的折叠。记作X(S) = SSSS…S(X个S)。
- 如果A = A’, B = B’,则AB = A’B’ 例如,因为3(A) = AAA, 2(B) = BB,所以3(A)C2(B) = AAACBB,而2(3(A)C)2(B) = AAACAAACBB
给一个字符串,求它的最短折叠。例如AAAAAAAAAABABABCCD的最短折叠为:9(A)3(AB)CCD。
解题思路:
一道挺不错的区间dp,适合我这种入门级选手做.定义f[i][j]为区间[i,j]压缩后的dp值,那么有两种状态转移:一,从[i,k],[k,j]直接转移;二,从[i,k]进行压缩转移,$f[i,j]=f[i,k]+2+m[(j-i+1)/(k-i+1)]$,其中需满足$(j-i+1)%(k-i+1)==0$.
code:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> #include<queue> #define R register #define next exnt #define debug puts("mlg") using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; inline ll read(); inline void write(ll x); inline void writesp(ll x); inline void writeln(ll x); ll n; char wn,c[1000]; ll f[150][150],m[120]; inline bool check(ll l,ll r,ll len){ for(R ll i=l+len;i<=r;i++){ if(c[(i-l)%len+l]!=c[i]) return false; } return true; } int main(){ while(!(('A'<=wn&&wn<='Z')||('a'<=wn&&wn<='z'))) wn=getchar(); while((('A'<=wn&&wn<='Z')||('a'<=wn&&wn<='z'))) c[++n]=wn,wn=getchar(); for(R ll i=1;i<=9;i++) m[i]=1; for(R ll j=10;j<=99;j++) m[j]=2; m[100]=3; memset(f,0x3f,sizeof f); for(R ll i=1;i<=n;i++) f[i][i]=1; for(R ll l=2;l<=n;l++){ for(R ll i=1,j=i+l-1;j<=n;j++,i++){ for(R ll k=i;k<j;k++) f[i][j]=min(f[i][j],f[i][k]+f[k+1][j]); for(R ll k=i;k<j;k++){ ll len=k-i+1; if(l%len) continue; if(check(i,j,len)) f[i][j]=min(f[i][j],f[i][k]+2+m[l/len]); } } } writeln(f[1][n]); } inline ll read(){ ll x=0,t=1;char ch=getchar(); while(ch<'0'||ch>'9'){ if(ch=='-') t=-1; ch=getchar(); } while(ch>='0'&&ch<='9'){ x=x*10+ch-'0'; ch=getchar(); } return x*t; } inline void write(ll x){ if(x<0){putchar('-');x=-x;} if(x<=9){putchar(x+'0');return;} write(x/10);putchar(x%10+'0'); } inline void writesp(ll x){ write(x);putchar(' '); } inline void writeln(ll x){ write(x);putchar(' '); }