您的位置:首页 > 其它

POJ 1159 Palindrome

2015-08-27 14:06 169 查看
Palindrome
Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 56756Accepted: 19631
DescriptionA palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
InputYour program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.
OutputYour program is to write to standard output. The first line contains one integer, which is the desired minimal number.
Sample Input
5
Ab3bd

Sample Output
2

题目大意:输出把当前字符串转换成回文串所要添加字符的最少字符
思路:最长公共子序列
普通的求最长公共子序列的方法会爆内存。滚动数组一发。
/* ***********************************************
Author        :PK28
Created Time  :2015/8/27 13:44:52
File Name     :4.cpp
************************************************ */
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
#include <list>
#include <deque>
#include <stack>
#define ull unsigned long long
#define ll long long
#define mod 90001
#define INF 0x3f3f3f3f
#define maxn 5000+10
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;

bool cmp(int a,int b){
return a>b;
}
int dp[2][maxn];
char s[maxn];
char t[maxn];
int main()
{
#ifndef ONLINE_JUDGE
//freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
int n;
while(cin>>n){
cin>>s;
strcpy(t,s);
reverse(t,t+n);
cle(dp);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
if(s[i-1]==t[j-1])dp[i%2][j]=dp[(i-1)%2][j-1]+1;
else dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]);
}
printf("%d\n",n-dp[n%2]
);
}
return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: