题解:P17750 「RSOI-2C」异或 / xor【出题人题解】

· · 题解

出题人题解。

思路

找性质题。

记 \text{msb}(x) 表示 x 的最高二进制位,则有:

  1. 若 \text{msb}(x) \not= \text{msb}(y),两点之间一定有边。
  2. 若 \text{msb}(x) = \text{msb}(y),两点之间一定无边。

:::info[证明] 对于性质 1,设 k=\min(\text{msb}(x),\text{msb}(y)),则 x \oplus y \geq 2^k > \min(x,y)。

对于性质 2,设 k=\text{msb}(x)=\text{msb}(y),则 x \oplus y < 2^k \leq \min(x,y)。

对于性质 3,0 \oplus x = x \geq 0=\min(0,x)。

因此可以按最高位分组,不同组之间完全连边。0 与任何点连边。

当 n=1 或 \exist a_i=0 或所有节点的最高位不同时图连通,答案是 0。

否则由于所有点的最高位 k 相同,只要把其中任意一个点改成 0 或改成最高位不为 k 的数,图就会变成以这个节点为中心的菊花图而连通。所以枚举每个点计算出它修改的最少代价,取最小值即可。

代码

:::success[AC Code]

#include<bits/stdc++.h>
#define int long long
#define pb push_back
using namespace std;
const int N = 1e5 + 5;
int a[N];
void solve(){
    int n; cin >> n;
    int minn = 1e18,cnt = 0;
    for(int i = 1;i <= n;i++){
        cin >> a[i];
        if(a[i] == 0) cnt++;
        minn = min(minn,a[i]);
    }
    if(n == 1){
        cout << 0;
        return;
    }
    for(int i = 1;i <= n;i++){
        if(a[i] == 0){
            cout << 0;
            return;
        }
    }
    int msb = 63 - __builtin_clzll(a[1]);
    bool fl = 1;
    for(int i = 1;i <= n;i++){
        if(63 - __builtin_clzll(a[i]) != msb){
            fl = 0;
            break;
        }
    }
    if(!fl){
        cout << 0;
        return;
    }
    int b1 = (1LL << msb) - 1,b2 = 1LL << (msb + 1),ans = 1e18;
    for(int i = 1;i <= n;i++) ans = min(ans,min(a[i] - b1,b2 - a[i]));
    cout << min(minn,ans);
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int tid,T = 1;
    while(T--) solve();
    return 0;
}

:::