洛谷P2470 [SCOI2007]压缩(区间dp)
题意
Sol
神仙题Orz
考虑区间dp,如果我们只设\(f[l][r]\)表示\(s_{lr}\)被压缩的最小长度,而不去关心内部\(M\)分布的话,可能在转移的时候转移出非法状态
因此考虑多加一维表示当前子串中有没有\(M\)(默认第一个字符为\(M\)不统计在内)
转移的时候就考虑不同的\(M\)对当前区间的贡献就可以。
\(P\)的作用实际上是将两个相同的字符串合成一个,拿hash判一下
复杂度\(O(n^3)\)
#include<bits/stdc++.h>
#define Pair pair<int, int>
#define MP(x, y) make_pair(x, y)
#define fi first
#define se second
#define LL long long
#define ull unsigned long long
#define Fin(x) {freopen(#x".in","r",stdin);}
#define Fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int MAXN = 501, mod = 1e9 + 7, INF = 1e9 + 10;
const double eps = 1e-9;
template <typename A, typename B> inline bool chmin(A &a, B b){if(a > b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline bool chmax(A &a, B b){if(a < b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline LL add(A x, B y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename A, typename B> inline void add2(A &x, B y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename A, typename B> inline LL mul(A x, B y) {return 1ll * x * y % mod;}
template <typename A, typename B> inline void mul2(A &x, B y) {x = (1ll * x * y % mod + mod) % mod;}
template <typename A> inline void debug(A a){cout << a << '\n';}
template <typename A> inline LL sqr(A x){return 1ll * x * x;}
inline int read() {
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int N, f[MAXN][MAXN], num[MAXN];
char s[MAXN];
ull po[MAXN], ha[MAXN], base = 131;
ull get(int l, int r) {
return ha[r] - ha[l - 1] * po[r - l + 1];
}
signed main() {
scanf("%s", s + 1);
N = strlen(s + 1);
memset(f, 0x3f, sizeof(f)); po[0] = 1;
for(int i = 1; i <= N; i++) f[i][i] = 1, num[i] = num[i / 10] + 1, ha[i] = ha[i - 1] * base + s[i], po[i] = po[i - 1] * base;
for(int len = 2; len <= N; len++) {
for(int l = 1; l + len - 1 <= N; l++) {
int r = l + len - 1;
for(int cur = 1; cur <= len; cur++) {
if(len % cur == 0) {
bool flag = 1;
for(int i = l; i + 2 * cur - 1 <= r; i++)
if(get(i, i + cur - 1) != get(i + cur, i + 2 * cur - 1)) {flag = 0; break;}
if(flag) chmin(f[l][r], f[l][l + cur - 1] + num[len / cur] + 2);
}
}
for(int k = l; k < r; k++) chmin(f[l][r], f[l][k] + f[k + 1][r]);
}
}
cout << f[1][N];
return 0;
}
/*
20
1 8 4 4 6 7 4 4 0 7 3 7 0 9 5 5 1 6 1 8
*/
}
作者:自为风月马前卒
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。