Codeforces——B. Longest Palindrome
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings “pop”, “noon”, “x”, and “kkkkkk” are palindromes, while strings “moon”, “tv”, and “abab” are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1≤n≤100, 1≤m≤50) — the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don’t print this line at all.
Examples
input
3 3
tab
one
bat
output
6
tabbat
input
4 2
oo
ox
xo
xx
output
6
oxxxxo
input
3 5
hello
codef
orces
output
0
input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
output
20
ababwxyzijjizyxwbaba
Note
In the first example, “battab” is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
题目大意
删除一些字符串,并重新排列剩下的字符串,使得到的字符串是回文,并且字符串的长度要尽可能的长。
题解
vector 容器中没有直接统计元素的函数
set 里面直接用count即可以
#include<iostream>
#include<algorithm>
#include<cstring>
#include<set>
#include<bits/stdc++.h>
using namespace std;
int n, m;
int main () {
set<string> ss;
string s, t, p = "", ans = "", r;
cin >> n >> m;
for(int i = 1; i <= n; i ++ ) {
cin >> s;
t = s;
reverse(t.begin(),t.end());
if(s == t) p = t; //最多只能选一个自身回文的字符串
else if(ss.count(t)) {
ans += t;
}
ss.insert(s);
}
r = ans;
reverse(ans.begin(), ans.end());
ans = ans + p + r;
cout << ans.size() << endl;
cout << ans << endl;
return 0;
}