题解:P14015 [ICPC 2024 Nanjing R] 生日礼物
考虑将偶数位非
对于上面的操作,如果没有
-
当
c_2 \le |c_0 - c_1| ,可以重复c_2 次给c_0 或c_1 加1 ,那么答案最多减少c_2 ,所以是|c_0 - c_1| - c_2 。 -
当
c_2 \le |c_0 - c_1| ,先分配掉|c_0 - c_1| 使得序列长度变为0 ,然后交替着把剩下的c_2 - |c_0 - c_1| 分配给c_0 和c_1 ,所以是(c_2 - |c_0 - c_1|) \bmod 2 。
时间复杂度
/*
* author: LostKeyToReach
* created time: 2025-09-10 16:04:41
*/
#include <bits/stdc++.h>
#define int long long
#define vi vt<int>
#define eb emplace_back
using ll = long long; using pii = std::pair<int, int>;
template<typename T> using vt = std::vector<T>;
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define S std::ios::sync_with_stdio(0), \
std::cin.tie(0), std::cout.tie(0)
template<typename T> T chkmax(T& x, T y) {
return (x < y) ? (x = y, y) : x;
} template<typename T> T chkmin(T& x, T y) {
return (x > y) ? (x = y, y) : x;
}int fio = (S, 0); constexpr int N = 5e5 + 5;
int32_t main() {
int t; std::cin >> t;
while (t--) {
std::string s;
std::cin >> s;
int n = sz(s); s = " " + s;
int a = 0, b = 0, c = 0;
for (int i = 1; i <= n; ++i) {
if (s[i] == '2') ++c;
else {
if (!(i & 1)) s[i] ^= 1;
(s[i] == '0' ? ++a : ++b);
}
}
if (c <= abs(a - b))
std::cout << abs(a - b) - c << "\n";
else
std::cout << (c - abs(a - b)) % 2 << "\n";
}
}