slongle
11/20/2017 - 11:59 AM

UVa 11404 - Palindromic Subsequence

UVa 11404 - Palindromic Subsequence

#include "bits/stdc++.h"
using namespace std;

typedef long long LL;
const int MAXN = 1e3 + 5;
const int MAXM = 1e5 + 5;
const int mod = 1e9 + 7;

int n, f[MAXN][MAXN], cnt;
char x[MAXN];
string g[MAXN][MAXN];

int main() {
    while (scanf(" %s", x + 1) != EOF) {
        n = strlen(x + 1);
        memset(f, 0, sizeof(f));
        for(int i=0;i<=n;i++) g[0][i]="";
        int len = 0;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++) {
                if (x[i] == x[n - j + 1]) {
                    f[i][j] = f[i - 1][j - 1] + 1;
                    g[i][j] = g[i - 1][j - 1] + x[i];
                    if (i == n - j + 1) len = max(len, f[i][j] * 2 - 1);
                    if (i<n - j + 1) len = max(len, f[i][j] * 2);
                }
                else {
                    f[i][j] = max(f[i - 1][j], f[i][j - 1]);
                    g[i][j] = max(g[i - 1][j], g[i][j - 1]);
                    if (f[i - 1][j]>f[i][j - 1]) {
                        f[i][j] = f[i - 1][j];
                        g[i][j] = g[i - 1][j];
                    }
                    else {
                        if (f[i - 1][j]<f[i][j - 1]) {
                            f[i][j] = f[i][j - 1];
                            g[i][j] = g[i][j - 1];
                        }
                        else {
                            f[i][j] = max(f[i - 1][j], f[i][j - 1]);
                            g[i][j] = min(g[i - 1][j], g[i][j - 1]);
                        }
                    }
                }
            }
        if (len%2==0){
            for(int i=0;i<len/2;i++) printf("%c",g[n][n][i]);
            for(int i=len/2-1;i>=0;i--) printf("%c",g[n][n][i]);
        }
        else{
            for(int i=0;i<len/2;i++) printf("%c",g[n][n][i]);
            for(int i=len/2;i>=0;i--) printf("%c",g[n][n][i]);   
        }
        puts("");
    }
    return 0;
}