Codeforces. Longest Palindrome[字符串处理]

Codeforces Round #620(Div.2) 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 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.

题意

给定n个长度为m的字符串,使用其中尽可能多的字符串构成一个回文串
输出回文串长度及该回文串(顺序可以乱)

分析

由于字符串长度相等,不存在用两个长度不同的字符串拼成回文串引发的更优解
由字符串构成的回文串应该满足前后对应的两个字符串对称,
中间的字符串满足自身回文或者没有中间字符串
在读入的时候便可以全都处理
这里使用string自带的函数处理字符串反转和字符串计数

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
#include <algorithm>
using namespace std;
inline int read() {
	register int x = 0, f = 1;
	register char c = getchar();
	while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0',c = getchar();
	return x * f;
}
set<string> queue;
int n, m;
string s, mid, temp, ansl, ansr, ans;
bool flag = false;
int main() {
	int n = read(), m = read();
	for (int i(1); i <= n; i++){
		cin >> s;
		temp = s;
		reverse(temp.begin(),temp.end());//反转
		if (s == temp) {
			if (!flag) mid = s, flag = true;//记录中间的自身回文串
		}
		else if (queue.count(temp)) ansl += s;//如果前面有s的反转串,则计入
		queue.insert(s);
	}
	ansr = ansl;
	reverse(ansr.begin(),ansr.end());//处理右边对应左边的串
	if (flag)//有自身回文串
		ans = ansl + mid + ansr;
	else //没有自身回文串
		ans = ansl + ansr;
	cout << ans.size() << endl << ans << endl;
	return 0;
}
posted @   ancer  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示