欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

洛谷P4302 [SCOI2003]字符串折叠(区间dp)

程序员文章站 2022-10-06 22:28:34
题意 "题目链接" Sol 裸的区间dp。 转移的时候枚举一下断点。然后判断一下区间内的字符串是否循环即可 cpp include define Pair pair define MP(x, y) make_pair(x, y) define fi first define se second de ......

题意

题目链接

sol

裸的区间dp。

转移的时候枚举一下断点。然后判断一下区间内的字符串是否循环即可

`cpp #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 */ }