【題解】Codeforces 1304B. Longest Palindrome

【題目敘述】http://codeforces.com/contest/1304/problem/B

#include <iostream>
using namespace std;
 
int n, m, l;
string s[105], ans1, ans2, mid;
 
int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i++){
        cin >> s[i];
    }
    for (int i = 0; i < n; i++){
        for (int j = i+1; j < n; j++){
            bool flag = true;
            if (s[i].length() && s[j].length()){
                for (int k = 0; k < m; k++){
                    if (s[i][k] != s[j][m-1-k]) flag = false;
                }
            }
            else flag = false;
            if (flag){
                ans1 += s[i];
                s[i] = "";
                ans2 = s[j] + ans2;
                s[j] = "";
            }
        }
    }
    for (int i = 0; i < n; i++){
        if (s[i].length()){
            bool flag = true;
            for (int j = 0; j < (m+1)/2; j++){
                if (s[i][j] != s[i][m-1-j]) flag = false;
            }
            if (flag){
                mid = s[i];
                break;
            }
        }
    }
    l = ans1.length() + ans2.length();
    if (mid.length()) l += mid.length();
    cout << l << "\n";
    cout << ans1;
    if (mid.length()) cout << mid;
    cout << ans2;
    cout << "\n";
}
分享本文 Share with friends