POJ 1159 Palindrome(最长公共子序列)

本文介绍了一种通过计算最长公共子序列来求解给定字符串转换为回文串所需的最少字符删除次数的方法。该方法将原字符串反转并与原字符串对比,找出两者之间的最长公共子序列,利用该子序列删除原字符串中的非公共部分即可得到回文串。

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

Palindrome

【题目链接】Palindrome

【题目类型】最长公共子序列

&题解:

你做的操作只能是插入字符,但是你要使最后palindrome,插入了之后就相当于抵消了,所以就和在这个串中删除最少的字符,使得它回文是一样的.

那么我们可以把这个串reverse,之后的串称为s2,找s2和s的最长公共子序列就好了,因为有了LCS,接着把其他的都删掉,就是一个回文串了,因为正着读和倒着读都一样
还有POJ居然能跑5000^2 我的923MS就跑完了,还是很快的嘛,当然这题还可以滚动数组,要对下标取模什么的也许就可以了吧,我用的是short来减小内存

&代码:

#include <cstdio>
#include <bitset>
#include <iostream>
#include <set>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
#define ll long long
#define fo(i,a,b) for(int i=(a);i<=(b);i++)
#define fd(i,a,b) for(int i=(a);i>=(b);i--)
#define cle(a,v) memset(a,(v),sizeof(a))
const int maxn = 5000 + 7;
short n, dp[maxn][maxn];
char s1[maxn], s2[maxn];
int main() {
#ifndef ONLINE_JUDGE
    freopen("E:1.in", "r", stdin);
#endif
    while(~scanf("%d", &n)) {
        cle(dp, 0);
        scanf("%s", s1);
        strcpy(s2, s1);
        reverse(s2, s2 + n);
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                if(s1[i - 1] == s2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
                else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
        // for(int i = 1; i <= n; i++) {
        //  for(int j = 1; j <= n; j++) {
        //      printf("%3d", dp[i][j]);
        //  }
        //  printf("\n");
        // }
        printf("%d\n", n - dp[n][n]);
    }
    return 0;
}

转载于:https://www.cnblogs.com/s1124yy/p/7206159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值