Codeforces 1304B. Longest Palindrome

Posted gredcomet

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces 1304B. Longest Palindrome相关的知识,希望对你有一定的参考价值。

根据数据范围,暴力可以解决,对每一个串,找与其互为回文的串,或者判断自身是否为回文串,然后两两将互为回文的串排列在头尾,中间放且只能最多放一个自身为回文串的串,因为题目说每个串都是不同的

技术图片
#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long LL;

string str[105];
int cache[105], self[105], s[105], chosen[105];

void run_case() {
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= n; ++i) 
        cin >> str[i];
    for(int i = 1; i <= n; ++i) {
        bool flag = true;
        for(int j = 0; j < m/2 && flag; ++j) {
            if(str[i][j] != str[i][m-j-1]) flag = false;
        }
        if(flag) {
            self[i] = 1;
            continue;
        }
        if(cache[i]) continue;
        string now = str[i];
        reverse(now.begin(), now.end());
        for(int j = 1; j <= n; ++j) {
            if(j != i && now == str[j]) {
                cache[i] = j; break;
            }
        }
    }
    vector<int> ans, selfs;
    int top = 0;
    for(int i = 1; i <= n; ++i)
        if(cache[i] && !chosen[i]) {
            ans.push_back(i);
            s[++top] = cache[i];
            chosen[cache[i]] = i;
        } else if(self[i]) selfs.push_back(i);
    if(selfs.size()) ans.push_back(selfs[0]);
    while(top) {
        ans.push_back(s[top--]);
    }
    cout << ans.size() * m << "
";
    for(auto i : ans) 
        cout << str[i];
}
 
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    //cout.setf(ios_base::showpoint);cout.precision(10);
    //int t; cin >> t;
    //while(t--)
    run_case();
    cout.flush();
    return 0;
}
View Code

 

以上是关于Codeforces 1304B. Longest Palindrome的主要内容,如果未能解决你的问题,请参考以下文章

CF1304B Longest Palindrome

Codeforces 1304E. 1-Trees and Queries

CF1304D Shortest and Longest LIS

CF1304D Shortest and Longest LIS

[CF1304D] Shortest and Longest LIS - 贪心

CodeForces 5C Longest Regular Backet sequence