题解:CF2158B Split
题目分析
我们需要将包含
解题思路
单个贡献:
- 奇数次出现的元素:无论如何分配,该元素在
p 和q 中的出现次数必为一奇一偶,因此对总贡献固定为1 。 - 偶数次出现的元素:
- 若能将其分配为在
p 和q 中均出现奇数次,则对总贡献为2 ; - 仅当该元素出现次数为
2n 且n 为偶数时,无法实现这种分配,其他偶数次出现的元素均可实现贡献2 。
- 若能将其分配为在
总贡献的计算:
-
记
m 为出现奇数次的元素个数,这部分总贡献为m 。 -
记
s 为可贡献2 的偶数次元素个数,初步总贡献为2 \times s 。 -
当
m>0 时,可通过调整奇数次元素的分配奇偶性,满足p 和q 的大小要求,总贡献为m + 2 \times s 。 -
当
m=0 时,所有元素均为偶数次,需保证分配到p 的元素总个数的奇偶性与n 一致:-
若
s 的奇偶性与n 相同,总贡献为2 \times s 。 -
否则,需将一个可贡献
2 的元素改为贡献0 ,总贡献为2 \times (s - 1) 。
-
::::success[AC代码]
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 4e5+10;
int t, a[N], cnt[N];
signed main() {
cin >> t;
while (t--) {
int n;
cin >> n;
memset(cnt, 0, sizeof(cnt));
for (int i = 1; i <= 2 * n; i++) {
cin >> a[i];
cnt[a[i]]++;
}
int m = 0; // 出现奇数次的元素个数
int s = 0; // 可贡献2的偶数次元素个数
for (int i = 1; i <= 2 * n; i++) {
if (cnt[i] == 0) continue;
if (cnt[i] % 2 == 1) {
m++;
} else {
// 当元素出现次数为2n且n为偶数时,无法双奇数分配
if (cnt[i] == 2 * n && n % 2 == 0) {
continue;
}
s++;
}
}
long long ans;
if (m > 0) {
ans = m + 2 * s;
} else {
// 所有元素均为偶数次,需保证分配奇偶性与n一致
if ((s % 2) == (n % 2)) {
ans = 2 * s;
} else {
ans = 2 * (s - 1);
}
}
cout << ans << '\n';
}
return 0;
}
::::