UVA11584-Partitioning by Palindromes(dp)

本文介绍了一种解决字符串划分问题的方法,目标是最小化回文串的数量。通过动态规划和预处理技巧,在O(n)时间内找到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

http://acm.hust.edu.cn/vjudge/problem/34398

题意

给定一个字符串,将其划分为若干个串,并且每个串都要是回文串,要求划分出来的回文串数目最小

思路

转移方程 d[i] = min(d[j] + 1) 其中s[j + 1] ~ s[i]要是回文串
其中状态O(n),转移O(n) 时间复杂度为O(n)。但是每次要判断s[j + 1] ~ s[i]是否为回文串,这样时间复杂度高达O(n^3)
因此,可现在O(n)的时间复杂度内预处理出j~i是否为回文串

代码

#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;

#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
#define CLR(a, x) memset(a, x, sizeof(a))
#define FILL(a, n, x) for (int i = 0; i < n; i++) a[i] = x

const int maxn = 3000 + 5;
const int INF = 0x3e3e3e3e;
char s1[maxn], s[maxn];
bool h[maxn][maxn];
int d[maxn];

int dp(int x) {
    if (d[x] != -1) return d[x];
    if (x < 0) return d[x] = 0;
    d[x] = INF;
    for (int i = -1; i < x; i++) {
        if (h[i + 1][x]) {
            //cout << i << ' ' << x << endl;
            d[x] = min(d[x], dp(i) + 1);
        }
    }
    return d[x];
}

int main() {
    int T;
    scan(T);
    while (T--) {
        memset(s, '\0', sizeof(s));
        memset(s1, '\0', sizeof(s1));
        scanf("%s", s1);
        int len = strlen(s1);
        for (int i = 0, j = 0; i < len; i++) {
            s[j++] = s1[i];
            s[j++] = '#';
        }
        len = strlen(s);
        s[len - 1] = '\0';
        len--;
        CLR(h, 0);
        for (int i = 0; i < len; i++) {
            h[i][i] = 1;
            int j = 1;
            while (i - j >= 0 && i + j < len) {
                int x = i - j, y = i + j;
                if (s[x] == s[y]) {
                    if (!(x & 1) && !(y & 1)) h[x / 2][y / 2] = 1; 
                    j++;
                } else {
                    break;
                }
            }
        }
        int n = strlen(s1);
        memset(d, -1, sizeof(d));
        int ans = dp(n - 1);
        printf("%d\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值