CF1822E Making Anti-Palindromes 题解
CF1822E Making Anti-Palindromes 题解
思路分析
首先去掉
然后我们记录下每一个字符的重复情况,即
然后我们可以对于每一个字符的重复情况两两互消。
剩下的仅仅可能有一个仍然重复的。
考虑下面的情况,
如果我们先吧
我们记录一个 std::vector<std::tuple<char, char, int>> 分别为消去的字符一,字符二,消去的数量。
这给了我们程序一个反悔的机会。
如果剩下的那一个字符与某一组的字符均不相同,则可以反悔这两个字符,分别与剩下的字符组合,如:
begin:
aa aa bb cc
treatment:
aa aa bc bc
repent:
ab ab ac ac
or
aa ab ac bc
即我们额外付出
如果还有剩的,就去原序列里面找不相同的
如果还有,则无解。
代码实现
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <tuple>
#include <vector>
constexpr int MaxN = 2e5 + 5;
int n;
int same[128];
char s[MaxN];
std::vector<char> ch;
std::vector<std::tuple<char, char, int>> rm;
void solve()
{
ch.clear();
rm.clear();
memset(same, 0, sizeof(same));
scanf("%d", &n);
scanf("%s", s + 1);
if (n % 2 == 1)
{
printf("%d\n", -1);
return;
}
for (int i = 'a'; i <= 'z'; i++)
{
ch.push_back(i);
}
for (int i = 1, j = n; i < j; i++, j--)
{
if (s[i] == s[j])
{
same[s[i]]++;
}
}
int answer = 0;
for (auto i : ch)
{
for (auto j : ch)
{
if (i == j)
{
continue;
}
int l = std::min(same[i], same[j]);
if (l == 0)
{
continue;
}
answer += l;
same[i] -= l;
same[j] -= l;
rm.push_back({i, j, l});
}
}
int k = 0;
char c = '\0';
for (int i = 'a'; i <= 'z'; i++)
{
if (same[i] != 0)
{
c = i;
k = same[i];
}
}
for (auto x : rm)
{
int i, j, l;
std::tie(i, j, l) = x;
if (i != c && j != c)
{
l = std::min(k, l * 2);
answer += (l + 1) / 2;
k -= l;
}
}
for (int i = 1, j = n; i < j; i++, j--)
{
if (s[i] != s[j] && s[i] != c && s[j] != c && k >= 1)
{
answer++;
k--;
}
}
printf("%d\n", k == 0 ? answer : -1);
}
int main()
{
int t;
scanf("%d", &t);
for (int i = 1; i <= t; i++)
{
solve();
}
return 0;
}