题解:P16495 踏青南陌上,寄远展壮游

· · 题解

诈骗题 \times 1。

题目要动态求特殊图中的连通块数量。

首先不难发现若要满足 a_u~\text{or}~a_v\neq 2^n-1,则需要 a_u,a_v 的 二进制上至少有一位都是 0。

然后就不会了。

但是观察样例以及手玩几组数据会发现除去 a_u=2^n-1 的情况之后(因为 a_u=2^n-1,所以对于任何 v 都有 a_u~\text{or}~a_v=2^n-1。)答案一般不会太大。那么为什么呢?

使用一开始发现的结论,若要满足 a_u~\text{or}~a_v\neq 2^n-1,则需要 a_u,a_v 的二进制上至少有一位都是 0。那么我们可以设 S_i 为所有二进制表示中第 i 位为 0 的 a_u 构成的集合。容易发现每个集合内部都是一个团(也就是两两都有连边),所以即使每两个集合之间一条边都没有(也就是每个集合是一个孤立的连通块),那最多也只会出现 n 个连通块。

所以用并查集模拟这最多 n 个连通块即可。若把并查集操作看作常数复杂度,则时间复杂度为 O(nq)。

:::success[代码]

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll N=65;

ll n,q,x,ans,fa[N];
bool vis[N];
vector<ll> roots;

inline ll find(ll x){return x==fa[x]?x:fa[x]=find(fa[x]);}

int main(){

    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);

    cin>>n>>q;
    for(int i=1;i<=n;i++) fa[i]=i;

    while(q--){

        cin>>x;
        ll y=(~x)&((1ll<<n)-1);

        if(y==0){cout<<(++ans)<<'\n';continue;}

        roots.clear();
        while(y){

            ll op=log2(y&-y);
            roots.push_back(find(op));
            y^=(1ll<<op);
        }

        sort(roots.begin(),roots.end());
        roots.erase(unique(roots.begin(),roots.end()),roots.end());

        if(roots.size()==1){

            ans+=(!vis[roots[0]]);
            vis[roots[0]]=true;
        }
        else{

            ll tot=0;
            for(auto x:roots) if(vis[x]) ++tot;
            ans=ans+1-tot;

            for(int i=1;i<(int)roots.size();i++) fa[roots[i]]=roots[0];
            vis[roots[0]]=true;
        }

        cout<<ans<<'\n';
    }

    return 0;
}

:::