UVA 11404 Palindromic Subsequence——dp

版权声明:欢迎大家转载,转载请注明出处 https://blog.csdn.net/hao_zong_yin/article/details/82055224

正反来一遍LCS就好了,然而没想到什么打印解的好办法,就拿string爆了一下。。。

随机测试的时候发现这样跑出来的有的不是回文串,不过前一半是回文串的一半,所以把前一半正反输出一遍就好了

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1010;
char s1[maxn], s2[maxn];
int dp[maxn][maxn];
string s[maxn][maxn];
int main() {
    //freopen("out.txt", "w", stdout);
    while (~scanf("%s", s1+1)) {
        int n = strlen(s1+1);
        for (int i = 1; i <= n; i++) s2[i] = s1[n-i+1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = 0, s[i][j].clear();
                if (s1[i] == s2[j]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                    s[i][j] = s[i-1][j-1];
                    s[i][j].push_back(s1[i]);
                }
                else if (dp[i-1][j] > dp[i][j-1]) {
                    dp[i][j] = dp[i-1][j];
                    s[i][j] = s[i-1][j];
                }
                else if (dp[i-1][j] < dp[i][j-1]) {
                    dp[i][j] = dp[i][j-1];
                    s[i][j] = s[i][j-1];
                }
                else {
                    dp[i][j] = dp[i-1][j];
                    s[i][j] = min(s[i-1][j], s[i][j-1]);
                }
            }
        }
        int len = s[n][n].size();
        if (len % 2) {
            for (int i = 0; i <= len/2; i++) cout << s[n][n][i];
            for (int i = len/2-1; i >= 0; i--) cout << s[n][n][i];
        }
        else {
            for (int i = 0; i < len / 2; i++) cout << s[n][n][i];
            for (int i = len/2-1; i >= 0; i--) cout << s[n][n][i];
        }
        cout << endl;
    }
    return 0;
}
/*
xdydd
*/

猜你喜欢

转载自blog.csdn.net/hao_zong_yin/article/details/82055224