题解:CF2246D diss_quack and Array Game

· · 题解

先对操作进行一些简化,把 Alice 在游戏开始后的操作看做在一个二进制数上,除以 2 相当于右移,减一相当于把最后一位变成 0,那么对于一个数 x,它变为 0 至少所需的操作数为 f(a_i) = \mathrm{popcount}(a_i) + \lfloor\log_2 a_i \rfloor。

考虑 Bob 怎么做才能尽可能阻挠 Alice。显然他每次只让 Alice 操作一个数,而不是多个数一起操作才是最优的。所以当有奇数在场时,他一定会使得序列中的第一个数是偶数,且第二个数是奇数;否则场上全是偶数时,他再怎么操作也无法阻挠 Alice。容易证明,只要场上至少存在一个奇数,那么他就能用一次交换操作构造出这种形态。因此在游戏开始时的 a_i 确定时,Bob 能使得 Alice 操作的最大轮数可以这么算:

考虑 Alice 在游戏开始之前如何操作。一个显然的想法是,Alice 一定会尽可能地增大 L_{\min} 的值。而 L_{\min} 的值只有 O(\log V) 个,所以我们可以暴力枚举并计算其贡献。

但是 Alice 不止可以增大 L_{\min},在 L_{\min} 确定时,对一个数进行操作,还可以减少一些 \mathrm{popcount}。但是减少的量也是有限制的,一个数最多可以减少 \log V 的代价,所以一个数不可能操作超过 \log V 次。我们可以暴力枚举每个数多进行操作的次数,选一个最优的统计进来即可。时间复杂度是 O(n\log^2 V) 的。

但是实际上这个复杂度是均摊的,每次增加的量必须是当前 L_{\min} 的倍数,否则就不满足限制了。因此一个数枚举的复杂度是 \sum_{i = 0}^{\log V} \dfrac{\log V}{2^i} = O(\log V) 的,均摊意义下总体复杂度 O(n\log V)。

#include <bits/stdc++.h>
#include <bits/extc++.h>
#define fi first
#define se second
#define eb(x) emplace_back(x)
#define pb(x) push_back(x)
#define lc(x) (tr[x].ls)
#define rc(x) (tr[x].rs)
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef long double ldb;
typedef __int128 i128;
using pi = pair<int, int>;
const int N = 1e5 + 10;
const ll inf = 0x3f3f3f3f3f3f3f3f;
ll n, a[N], ans;

int highbit(int x) {
    for(int i = 25; i >= 0; i--) {
        if((x >> i) & 1) {
            return i;
        }
    }
    return 0;
}

int lowbit(int x) {
    return (x & (-x));
}

int popc(int x) {
    return __builtin_popcount(x);
}

void solve()
{
    ans = inf;
    cin >> n;
    ll res = 0;
    for(int i = 1; i <= n; i++) {
        cin >> a[i];
        res += highbit(a[i]) + popc(a[i]);
    }
    ans = min(ans, res);
    for(int i = 0; i <= 20; i++) {
        res = 0;
        for(int j = 1; j <= n; j++) {
            int s = (2 << i) - 1, ad = 0;
            if((a[j] & s) != 0) {
                ad = (2 << i) - (a[j] & s);
            }
            res += ad;
            ll xares = inf;
            for(int k = 0; k <= 64; k += (1 << i)) {
                if(k & s) continue;
                int xa = (a[j] + ad + k) >> (i + 1);
                xares = min(xares, (ll) highbit(xa) + popc(xa) + k);
            }
            res += xares;
        }
        res += i + 1;
        ans = min(ans, res);
    }
    cout << ans << "\n";
}

int main()
{
    // freopen("CF_2246_D.in", "r", stdin);
    // freopen("CF_2246_D.out", "w", stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int T;
    cin >> T;
    while(T--) solve();
    return 0;
}