POJ 1159 - Palindrome (DP 添加最少字符使s为回文串)

来源:互联网 发布:coc墙升级数据 编辑:程序博客网 时间:2024/05/21 09:16

Palindrome

Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 52290 Accepted: 18026

Description

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.

Input

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.

Output

Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

Sample Input

5Ab3bd

Sample Output

2

Source

IOI 2000


题意:

输入字符串s,求最少添加多少个字符,使得s是一个回文串。


思路:

一:

DP dp[i][j] 表示s[i...j]变为回文串最少需要添加的字符数,

dp[i][j] = min({if s[i]==s[j]: dp[i-1][j-1]},dp[i+1][j]+1, dp[i][j-1]+1);


二:

设原序列S的逆序列为S'

最少需要补充的字母数 = 原序列S的长度 —  S和S'的最长公共子串长度


由于内存比较少,所以需要优化一下,因为对于当前i的值,来至于i和i+1,所以dp[2][maxn]就够了



#include <cstdio>#include <iostream>#include <vector>#include <algorithm>#include <cstring>#include <string>#include <map>#include <cmath>#include <queue>#include <set>using namespace std;//#define WIN#ifdef WINtypedef __int64 LL;#define iform "%I64d"#define oform "%I64d\n"#define oform1 "%I64d"#elsetypedef long long LL;#define iform "%lld"#define oform "%lld\n"#define oform1 "%lld"#endif#define S64I(a) scanf(iform, &(a))#define P64I(a) printf(oform, (a))#define P64I1(a) printf(oform1, (a))#define REP(i, n) for(int (i)=0; (i)<n; (i)++)#define REP1(i, n) for(int (i)=1; (i)<=(n); (i)++)#define FOR(i, s, t) for(int (i)=(s); (i)<=(t); (i)++)const int INF = 0x3f3f3f3f;const double eps = 10e-9;const double PI = (4.0*atan(1.0));const int maxn = 5000 + 20;char str[maxn];int dp[2][maxn];int main() {    int n;    while(scanf("%d", &n) != EOF) {        scanf("%s", str);        memset(dp, 0, sizeof(dp));        int ans = INF;        for(int i=n-1; i>=0; i--) {            for(int j=i; j<n; j++) {                int c = i % 2;                if(i == j) {                    dp[c][j] = 0;                    continue;                }                int t = dp[c^1][j] + 1;                if(str[i] == str[j]) t = min(t, dp[1^c][j-1]);                t = min(t, dp[c][j-1] + 1);                dp[c][j] = t;            }        }        printf("%d\n", dp[0][n-1]);    }    return 0;}




0 0
原创粉丝点击