• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ACM s1124yy
守りたいものが 強くさせること
博客园    首页    新随笔    联系   管理     

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

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;
}

posted @ 2017-07-19 15:46  s1124yy  阅读(198)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3