给定一个由 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 ∣t∣≥⌊2∣s∣⌋(其中 ∣ 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 2≤∣s∣≤106 ). 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 ∣t∣≥⌊2∣s∣⌋ .
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).
cacbac
aba
abc
a
cbacacacbcbababacbcb
cbaaacbcaaabc
In the first example, other valid answers include “cacac”, “caac”, “aca” and “ccc”.
由于题目中只要求找到长度不低于 ∣ s ∣ 2 \frac{|s|}{2} 2∣s∣ 的回文子序列,所以不用考虑是否连续。只要每次在当前字符串长度范围(初始范围为整个字符串)内取首两位与末两位,由于字符串只由 a
,b
,c
组成,所以必定有两位相同,抛弃不同的两位,将这两位定位新的区间,重复以上操作。由于每次操作抛弃两位,是 4 4 4 的 1 2 \frac{1}{2} 21 ,所以不存在无解情况。
#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;
}
吐槽:这绿题质量*******