B. Longest Palindrome
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
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.
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m,ans,st[105],top;
char s[105][105];
bool used[105];
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)scanf("%s",s[i]+1);
for(int i=1;i<=n;i++) 第一层循环
{
if(used[i])continue;
bool found=0;
for(int j=i+1;j<=n;j++) 第二层循环 将该行字符串与他下面进行比较
{
if(used[j])continue;
bool f=1;
for(int k=1;k<=m;k++) { 对于是否存在 成一对 的回文字符串的判断
if(s[i][k]!=s[j][k] || s[i][k] != s[i][m-k+1])
f=0;
}
if(f)
{
used[j]=1;
found=1;
break;
}
f=1;
for(int k=1;k<=m;k++) 对于是否构成 回文字串
if(s[i][k]!=s[j][m-k+1])
f=0;
if(f)
{
used[j]=1;
found=1;
break;
}
}
if(found)
{
used[i]=1; used 数组用于标记被取出的字串
st[++top]=i; 存储可构成回文字串的字串
ans+=2;
}
}
int x=0;
for(int i=1;i<=n;i++) 在上面标记完所有的成对的且本就是回文的字符串后,再次寻找是否存在独自存在的字串并只标记一个
{
if(used[i])continue;
bool f=1;
for(int k=1;k<=m;k++)
if(s[i][k]!=s[i][m-k+1])
f=0;
if(f)
{
ans++;
x=i; 均为标记字串所在行
break;
}
}
printf("%d\n",ans*m);
for(int i=1;i<=top;i++)printf("%s",s[st[i]]+1); 正序输出字符串
if(x)printf("%s",s[x]+1); 输出不成对的本是回文的字串
for(int i=top;i>=1;i--) 最后倒序输出字串 形成回文串
{
for(int j=m;j>=1;j--)
putchar(s[st[i]][j]);
}
putchar('\n');
return 0;
}