跳到正文

题解

题解:P14015 [ICPC 2024 Nanjing R] 生日礼物

lkrqwq约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
P14015

版本

  1. v1当前

考虑将偶数位非 22 的数字翻转,那么问题就等价于每次删相邻不同的字符。

对于上面的操作,如果没有 22,最终序列的长度肯定是 ∣c0−c1∣|c_0 - c_1|,cxc_x 表示 xx 的出现次数。如果有 22 的话,可以分类讨论一下。

  • 当 c2≤∣c0−c1∣c_2 \le |c_0 - c_1|,可以重复 c2c_2 次给 c0c_0 或 c1c_1 加 11,那么答案最多减少 c2c_2,所以是 ∣c0−c1∣−c2|c_0 - c_1| - c_2。

  • 当 c2≤∣c0−c1∣c_2 \le |c_0 - c_1|,先分配掉 ∣c0−c1∣|c_0 - c_1| 使得序列长度变为 00,然后交替着把剩下的 c2−∣c0−c1∣c_2 - |c_0 - c_1| 分配给 c0c_0 和 c1c_1,所以是 (c2−∣c0−c1∣) mod 2(c_2 - |c_0 - c_1|) \bmod 2。

时间复杂度 O(n)O(n)。

C++
/*
 * 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";
    }
}
原文