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 nn distinct strings of equal length mm. 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 nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.
Next nn lines contain a string of length mm 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.ExamplesinputCopy
3 3
tab
one
bat
outputCopy
6
tabbat
inputCopy
4 2
oo
ox
xo
xx
outputCopy
6
oxxxxo
inputCopy
3 5
hello
codef
orces
outputCopy
0
inputCopy
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
outputCopy
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.
思路:暴力,对每个字符串进行reverse,如果和本身相同放中间,剩下相同的一个前头放,一个后头放。模拟即可
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=150;
typedef long long LL;
string str[maxn];
LL num1[maxn],num2[maxn];
bool vis[maxn];
int main(void)
{
LL n,m;cin>>n>>m;
LL cnt1=0;LL cnt2=0;
for(int i=0;i<n;i++) cin>>str[i];
//先统计自身不是回文串的
for(LL i=0;i<n;i++)
{
if(!vis[i])
{
string k=str[i];reverse(k.begin(),k.end());
for(LL j=i+1;j<n;j++)
{
if(k==str[j]&&!vis[j])
{
num1[++cnt1]=i;
num2[++cnt2]=j;
vis[i]=true;vis[j]=true;
break;
}
}
}
}
for(LL i=0;i<n;i++)
{
string k=str[i];reverse(k.begin(),k.end());
if(k==str[i])
{
num1[++cnt1]=i;break;
}
}
cout<<(cnt1+cnt2)*m<<endl;
for(LL i=1;i<=cnt1;i++)
cout<<str[num1[i]];
for(LL j=cnt2;j>=1;j--)
cout<<str[num2[j]];
return 0;
}