您的位置:首页 > 其它

hdu-1513 Palindrome

2015-08-12 20:45 190 查看

Palindrome

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

Total Submission(s): 4157    Accepted Submission(s): 1420


[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

 

与最长公共子串类似。

开始默认以字符串中间字母为对称轴,拆为两个字符串进行计算,之后用字符串长度减去相应地公共子串长度,wrong了好几发,没找到错误原因。

之后借鉴大神代码改了dp方程:

for (int i=n-2; i>=0; i--) {

            for (int j=i+1; j<n; j++) {

                if (s[i]==s[j]) {

                    lcs[i%2][j]=lcs[(i+1)%2][j-1];

                }

                else {

                    lcs[i%2][j]=min(lcs[(i+1)%2][j],lcs[i%2][j-1])+1;

                }

            }

        }

dp方程中用到了滚动数组,防止5000*5000内存炸了。

dp方程内容与最长公共子串类似,但是将字符串分为两部分,计算公共字串。若两边字符相等,则dp[i][j]不变,否则取右方与上方最小值加一,表示需加入一个字符构成回文。

下面是代码:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define Max 200005

string s1,s2,s;
int lcs[5][5505];

int main(){
int n;
while (cin>>n) {
cin>>s;
memset(lcs, 0, sizeof(lcs));
for (int i=n-2; i>=0; i--) {
for (int j=i+1; j<n; j++) {
if (s[i]==s[j]) {
lcs[i%2][j]=lcs[(i+1)%2][j-1];
}
else {
lcs[i%2][j]=min(lcs[(i+1)%2][j],lcs[i%2][j-1])+1;
}
}
}
cout<<lcs[0][n-1]<<endl;
}

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