2018.07.31 bzoj4569: [Scoi2016]萌萌哒(并查集+倍增)

时间:2021-08-14 15:41:17

传送门

对于每个限制,使用倍增的二进制拆分思想,用并查集数组fa[i][j]" role="presentation" style="position: relative;">fa[i][j]fa[i][j]表示从i" role="presentation" style="position: relative;">ii开始,延伸2j" role="presentation" style="position: relative;">2j2j的区间所属的集合,这样的话,我们将所有限制拆分过后,从上向下传递标记直到长度为1" role="presentation" style="position: relative;">11的区间,最后统计有多少长度为1" role="presentation" style="position: relative;">11的区间的祖先是自己即可。

代码:

#include<bits/stdc++.h>
#define mod 1000000007
using namespace std;
int fa[100005][25],cnt=-1,n,m,l1,r1,l2,r2;
inline int find(int x,int y){return fa[x][y]==x?fa[x][y]:fa[x][y]=find(fa[x][y],y);}
inline void merge(int x,int y,int l){int fx=find(x,l),fy=find(y,l);if(fx!=fy)fa[fx][l]=fy;}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;++i)for(int j=0;j<=20;++j)fa[i][j]=i;
    while(m--){
        scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
        for(int i=20;~i;--i)if(l1+(1<<i)<=1+r1)merge(l1,l2,i),l1+=(1<<i),l2+=(1<<i);
    }
    for(int i=20;i;--i)
        for(int j=1;j+(1<<i)<=1+n;++j)merge(j,find(j,i),i-1),merge(j+(1<<i-1),fa[j][i]+(1<<i-1),i-1);
    long long ans=9;
    for(int i=1;i<=n;++i)if(find(i,0)==i)++cnt;
    while(cnt--)ans=ans*10%mod;
    printf("%lld",ans);
    return 0;
}