BZOJ 1090: [SCOI2003]字符串折叠( 区间dp )
按照题意dp...dp(l, r) = min{ dp(l, x) + dp(x+1, r) , 折叠(l, r) }
折叠(l, r)我是直接枚举长度然后哈希判..
--------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int maxn = 109;
const int p = 101;
char S[maxn];
int d[maxn][maxn], N;
ull h[maxn], K[maxn];
bool check(int l1, int r1, int l2, int r2) {
return h[l1] - h[r1 + 1] * K[r1 - l1 + 1] == h[l2] - h[r2 + 1] * K[r2 - l2 + 1];
}
int cnt(int x) {
int ret = 0;
for(; x; x /= 10) ret++;
return ret + 2;
}
int dp(int l, int r) {
int &t = d[l][r];
if(t != -1) return t;
int len = r - l + 1;
t = len;
for(int i = len / 2; i; i--) if(len % i == 0 && check(l, r - i, l + i, r))
t = min(t, cnt(len / i) + dp(l, l + i - 1));
for(int i = l; i < r; i++)
t = min(t, dp(l, i) + dp(i + 1, r));
return t;
}
int main() {
scanf("%s", S); N = strlen(S);
K[0] = 1; h[N] = 0;
for(int i = 1; i <= N; i++) K[i] = K[i - 1] * p;
for(int i = N; i--; ) h[i] = h[i + 1] * p + S[i];
memset(d, -1, sizeof d);
for(int i = 0; i < N; i++) d[i][i] = 1;
printf("%d\n", dp(0, N - 1));
return 0;
}
--------------------------------------------------------------
1090: [SCOI2003]字符串折叠
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 826 Solved: 533
[Submit][Status][Discuss]
Description
折叠的定义如下: 1. 一个字符串可以看成它自身的折叠。记作S S 2. X(S)是X(X>1)个S连接在一起的串的折叠。记作X(S) SSSS…S(X个S)。 3. 如果A A’, BB’,则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。
Input
仅一行,即字符串S,长度保证不超过100。
Output
仅一行,即最短的折叠长度。
Sample Input
NEERCYESYESYESNEERCYESYESYES
Sample Output
14
HINT
一个最短的折叠为:2(NEERC3(YES))
Source