标签:nta div case com break bcd head ack algorithm
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.
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.
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.
3 3
tab
one
bat
6 tabbat
4 2
oo
ox
xo
xx
6 oxxxxo
3 5
hello
codef
orces
0
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
20 ababwxyzijjizyxwbaba
题意:给n个长度为m的不同字符串,找出回文串并拼接在一起,输出最长的回文串.
分析:输出的答案应为s1...s1+s2+s3...s3,其(s1,s3)为一对回文串,在他们的中间加上任意一个自身回文的字符串,这样题目就能直接出答案了,我们直接先遍历一边字符串数组,找到对回文串,并将其标记(防止他是自身回文在下面重复记录),然后再找自身回文(只需任意一个就行,多了反而不满足条件)
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <string.h> #include <math.h> #include <algorithm> #include <stack> #include <queue> #include <vector> #include <map> #include <set> #define ll long long const int N=1e6+10; using namespace std; typedef pair<int,int>PII; int n,m; int q=0,p=0; string s[N]; //字符串的容器 string ans1[N],ans2[N]; //记录回文串 string tmp; //记录反转后的字符串 map<string,int> w; //用来标记 int main(){ ios::sync_with_stdio(false); 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++){ tmp=s[j]; reverse(tmp.begin(),tmp.end()); if(s[i]==tmp){ w[s[i]]=2; ans1[q++]=s[i]; break; } } for(int i=0;i<n;i++){ tmp=s[i]; reverse(tmp.begin(),tmp.end()); if(s[i]==tmp && w[s[i]]!=2){ ans2[p++]=s[i]; break; } } cout<<q*m*2+p*m<<endl; for(int i=0;i<=q;i++){ cout<<ans1[i]; reverse(ans1[i].begin(),ans1[i].end()); } cout<<ans2[0]; for(int i=q;i>=0;i--) cout<<ans1[i]; return 0; }
标签:nta div case com break bcd head ack algorithm
原文地址:https://www.cnblogs.com/lr599909928/p/12334141.html