您的位置:首页 > 其它

hdu_1513 Palindrome

2016-09-12 11:11 225 查看

Palindrome

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 5332 Accepted Submission(s): 1826


[align=left]Problem Description[/align]
A 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.

[align=left]Input[/align]
Your 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.

[align=left]Output[/align]
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

[align=left]Sample Input[/align]

5
Ab3bd

[align=left]Sample Output[/align]

2

求出题目所给字符串与其反字符串的最长公共子序列,n-最长公共子序列的长度即可

数据比较大,得用滚动数组优化空间

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <stack>
#include <bitset>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#define FOP freopen("data.txt","r",stdin)
#define inf 0x3f3f3f3f
#define maxn 1000010
#define mod 1000000007
#define PI acos(-1.0)
#define LL long long
using namespace std;

int n;
char a[5010], b[5010];
int dp[3][5010];
int main()
{
while(scanf("%d", &n) != EOF){
scanf("%s", a + 1);
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++){
b[i] = a[n-i+1];
}
for(int x = 1; x <= n; x++){
for(int y = 1; y <= n; y++){
if(a[x] == b[y]){
dp[x%2][y] = dp[(x-1)%2][y-1] + 1;
}
else{
dp[x%2][y] = max(dp[(x-1)%2][y], dp[x%2][y-1]);
}
}
}
printf("%d\n", n - dp[n%2]
);
}

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