lightoj1033 - Generating Palindromes (LCS)

来源:互联网 发布:淘宝微瑕疵冰箱骗局 编辑:程序博客网 时间:2024/04/29 05:22

题意:给你一个字符串,至少需要添加多少字符可以使得它变成一个回文串.

思路 :设串S的反串为S‘那么strlen(S) - LCS(S, S')就是本问题的答案.

如:

S(原串)       A   b  3  b  d

S1(倒序串)   d   b  3  b  A

LCS                   b  3  b

 

      所以,有3个字符已经配对,不用添加字符就能够成回文,需要添加的字母仅有“A”与“d”。

/*********************************************** * Author: fisty * Created Time: 2015-08-19 14:39:16 * File Name   : 1033.cpp *********************************************** */#include <iostream>#include <cstring>#include <deque>#include <cmath>#include <queue>#include <stack>#include <list>#include <map>#include <set>#include <string>#include <vector>#include <cstdio>#include <bitset>#include <algorithm>using namespace std;#define Debug(x) cout << #x << " " << x <<endl#define Memset(x, a) memset(x, a, sizeof(x))const int INF = 0x3f3f3f3f;typedef long long LL;typedef pair<int, int> P;#define FOR(i, a, b) for(int i = a;i < b; i++)#define lson l, m, k<<1#define rson m+1, r, k<<1|1#define MAX_N  1100char s[MAX_N];char _s[MAX_N];int t;int dp[MAX_N][MAX_N];int solve(int n){    Memset(dp, 0);    for(int i = 1;i <= n; i++){        for(int j = 1; j <= n; j++){            if(s[i] == _s[j]){                dp[i][j] = dp[i-1][j-1] + 1;            }else{                dp[i][j] = max(dp[i-1][j], dp[i][j-1]) ;            }        }    }    return dp[n][n];}int main() {    //freopen("in.cpp", "r", stdin);    //cin.tie(0);    //ios::sync_with_stdio(false);    scanf("%d", &t);    int cnt = 1;    while(t--){        Memset(s, 0);        Memset(_s, 0);        scanf("%s", s+1);        int n = strlen(s+1);        for(int i = 1;i <= n; i++){            _s[i] = s[n-i+1];        }        printf("Case %d: %d\n", cnt++,n - solve(n));       }    return 0;}


0 0
原创粉丝点击