BZOJ3237: [Ahoi2013]连通图 cdq分治+并查集

首先连通图问题 用并查集维护很显然
看到k的范围 铁铁的 nlogn 因为是离线询问 我们很容易就能想到用cdq分治来维护并查集
对于两个集合 s1,s2 我们可以把不属于 s1,s2 的边都先存到并查集里 将 s1 中不属于 s2 的边加进去 这时候就可以判断 s2 这个集合是否满足了 之后我们将之前加进去的边删掉 再加入 s2 中不属于 s1 的就又可以做 s1
中间的维护过程可以在并查集的基础上加一个栈 暴力更改

#include<bits/stdc++.h>
#define bug(x) cout<<(#x)<<" "<<(x)<<endl
using namespace std;
const int N=1e5+5;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int n,m,k,tim=1,top,f[N],st1[N*10],st2[N*10],vis[N*2];
struct Edge{
    int u,v;
}e[N*2];
struct node{
    int c[4],cnt;
}q[N];
bool ans[N];
int find(int x){
    if(f[x]==x) return x;
    int y=find(f[x]);
    st1[++top]=x,st2[top]=f[x],f[x]=y;
}
void cdq(int l,int r){
    int Top=top;
    if(l==r){
        for(int i=0;i<q[l].cnt;i++) if(find(e[q[l].c[i]].u)!=find(e[q[l].c[i]].v)) {
            ans[l]=1;
            break;
        }
        while(Top!=top) f[st1[top]]=st2[top],--top;
        return ;
    }
    int mid=(l+r)>>1;++tim;
    for(int i=l;i<=mid;i++)
        for(int j=0;j<q[i].cnt;j++)
            vis[q[i].c[j]]=tim;
    for(int i=mid+1;i<=r;i++)
        for(int j=0;j<q[i].cnt;j++)
            if(vis[q[i].c[j]]!=tim){
                int x=find(e[q[i].c[j]].u),y=find(e[q[i].c[j]].v);
                if(x!=y) st1[++top]=x,st2[top]=f[x],f[x]=y;
            }
    cdq(l,mid);++tim;
    while(Top!=top) f[st1[top]]=st2[top],--top;
    for(int i=mid+1;i<=r;i++)
        for(int j=0;j<q[i].cnt;j++)
            vis[q[i].c[j]]=tim;
    for(int i=l;i<=mid;i++)
        for(int j=0;j<q[i].cnt;j++)
            if(vis[q[i].c[j]]!=tim){
                int x=find(e[q[i].c[j]].u),y=find(e[q[i].c[j]].v);
                if(x!=y) st1[++top]=x,st2[top]=f[x],f[x]=y;
            }
    cdq(mid+1,r);
    while(Top!=top) f[st1[top]]=st2[top],--top;
}
int main(){
#ifdef Devil_Gary
    freopen("in.txt","r",stdin);
#endif
    n=read(),m=read();
    for(int i=1;i<=m;i++) e[i].u=read(),e[i].v=read();
    k=read();
    for(int i=1;i<=k;i++){
        q[i].cnt=read();
        for(int j=0,x;j<q[i].cnt;j++)
            x=read(),q[i].c[j]=x,vis[x]=tim; 
    }
    for(int i=1;i<=n;i++) f[i]=i;
    for(int i=1;i<=m;i++)
        if(vis[i]!=tim){
            int x=find(e[i].u),y=find(e[i].v);
            if(x!=y) f[x]=y;
        }
    top=0,cdq(1,k);
    for(int i=1;i<=k;i++) if (!ans[i]) printf("Connected\n");
        else printf("Disconnected\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值