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
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.

题意:
给你n个串,问你能否选几个串构成最长回文串

解析:

会出现两种情况
第一种: 自身就是回文串 比如 aa
第二种: 选择两个串构成回文 比如 ab ba

那么对于第一种情况 肯定是放在中间的,因为只出现一次,肯定放在回文中间

对于第二种放在两边即可

#include<bits/stdc++.h>
using namespace std;
int n,m;
int vis[100005];
string s[10005];
vector<pair<string,int> > v;
int main()
{
	string ch;
	cin>>n>>m;
	int k;
	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++)
		{
			if(vis[i]==1||vis[j]==1) continue;
			int flag=0;
			for(int k=0;k<m;k++)
			{
				if(s[i][k]!=s[j][m-k-1])
				{
					flag=1;
					break;
				}	
			}
			if(flag==0)
			{
				vis[i]=1;
				vis[j]=1;
				ch+=s[i];
			//	cout<<ch<<endl;
			}
		}
	}
//cout<<ch<<endl;
	string str;
	for(int i=0;i<n;i++)
	{
		if(vis[i]) continue;
		int flag=0;
		for(int k=0;k<m;k++)
		{
			if(s[i][k]!=s[i][m-k-1]) 
			{
				flag=1;
				break;
			}
		}
		if(flag==0)
		{
			str+=s[i];
			break;
		}
	}
	cout<<ch.size()*2+str.size()<<endl;
	cout<<ch;
	cout<<str;
	reverse(ch.begin(),ch.end());
	cout<<ch<<endl;
}
发布了412 篇原创文章 · 获赞 8 · 访问量 8854

猜你喜欢

转载自blog.csdn.net/qq_43690454/article/details/104356808