CF1178E Archaeology题解

Archaeology

传送门

题面翻译

给定一个由 a,b,c组成的字符串 s s s

s s s 没有两个相邻的字符是相同的。

现在需要你求出字符串 s s s 的一个回文子序列 t t t,且满足 ∣ t ∣ ≥ ⌊ ∣ s ∣ 2 ⌋ |t|\ge\left\lfloor\dfrac{|s|}{2}\right\rfloor t2s(其中 ∣ S ∣ |S| S 表示字符串 S S S 的长度)。

如果有多种情况,输出任意一个即可。

如果没有满足要求的字符串 t t t,输出IMPOSSIBLE

题目描述

Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor’s Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?

The book contains a single string of characters “a”, “b” and “c”. It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides.

Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don’t have to maximise the length of it.

A string a a a is a subsequence of a string b b b if a a a can be obtained from b b b by deletion of several (possibly, zero or all) characters.

输入格式

The input consists of a single string s s s ( 2 ≤ ∣ s ∣ ≤ 1 0 6 2 \leq |s| \leq 10^6 2s106 ). The string s s s consists only of characters “a”, “b”, “c”. It is guaranteed that no two consecutive characters are equal.

输出格式

Output a palindrome t t t that is a subsequence of s s s and ∣ t ∣ ≥ ⌊ ∣ s ∣ 2 ⌋ |t| \geq \lfloor \frac{|s|}{2} \rfloor t2s .

If there are multiple solutions, you may print any of them. You don’t have to maximise the length of t t t .

If there are no solutions, output a string “IMPOSSIBLE” (quotes for clarity).

样例 #1

样例输入 #1

cacbac

样例输出 #1

aba

样例 #2

样例输入 #2

abc

样例输出 #2

a

样例 #3

样例输入 #3

cbacacacbcbababacbcb

样例输出 #3

cbaaacbcaaabc

提示

In the first example, other valid answers include “cacac”, “caac”, “aca” and “ccc”.

解题思路

由于题目中只要求找到长度不低于 ∣ s ∣ 2 \frac{|s|}{2} 2s 的回文子序列,所以不用考虑是否连续。只要每次在当前字符串长度范围(初始范围为整个字符串)内取首两位与末两位,由于字符串只由 a,b,c组成,所以必定有两位相同,抛弃不同的两位,将这两位定位新的区间,重复以上操作。由于每次操作抛弃两位,是 4 4 4 1 2 \frac{1}{2} 21 ,所以不存在无解情况。

AC Code

#include 
using namespace std;
#define int long long
const int Maxn = 1e6 + 5;
char s[Maxn];
int len, l, r;
char ans[Maxn];
inline void work() {
	cin >> s + 1;
	l = 1, r = strlen(s + 1);
	while (r - l + 1 >= 4) {
		if (s[l] == s[r]) {
			ans[len++] = s[l];
			l += 2;
			r -= 2;
		} else if (s[l + 1] == s[r]) {
			ans[len++] = s[l + 1];
			l += 2;
			r -= 2;
		} else if (s[l] == s[r - 1]) {
			ans[len++] = s[l];
			l += 2;
			r -= 2;
		} else if (s[l + 1] == s[r - 1]) {
			ans[len++] = s[l + 1];
			l += 2;
			r -= 2;
		}
	}
	for (int i = 0; i < len; i++) {
		cout << ans[i];
	}
	if (l < r) {
		cout << s[l];
	}
	for (int i = len - 1; i >= 0; i--) {
		cout << ans[i];
	}
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	work();
	return 0;
}

吐槽:这绿题质量*******

你可能感兴趣的:(题解,c++,c语言)