noip模拟77 (2)

image


代码如下:

AC_code #include<bits/stdc++.h> #define re register int #define ii inline int #define iv inline void #define f() cout<<"fuck"<<endl #define head heeead #define next neet using namespace std; const int N=5e5+10; int n,m,cnt,timi,tot; struct node { int x,y; }cun[N]; int to[N<<1],next[N<<1],head[N]; int fa[N],size[N],son[N],top[N],deep[N]; int B[N],J[N],st[N],be[N]; bool vis[N],in[N]; ii read() { int x=0;char ch=getchar();bool f=1; while(ch<'0' or ch>'9') { if(ch=='-') f=0; ch=getchar(); } while(ch>='0' and ch<='9') { x=(x<<1)+(x<<3)+(ch^48); ch=getchar(); } return f?x:(-x); } iv add(int x,int y) { to[++tot]=y; next[tot]=head[x]; head[x]=tot; } ii get_B(int x) {return B[x]==x?x:B[x]=get_B(B[x]);} ii get_J(int x) {return J[x]==x?x:J[x]=get_J(J[x]);} iv dfs(int st,int f,int g) { vis[st]=1; be[st]=g; fa[st]=f; size[st]=1; deep[st]=deep[f]+1; for(re i=head[st];i;i=next[i]) { int p=to[i]; if(vis[p]) continue; dfs(p,st,g); size[st]+=size[p]; son[st]=(size[son[st]]>size[p])?son[st]:p; } } iv dfs2(int st,int t) { top[st]=t; if(!son[st]) return; dfs2(son[st],t); for(re i=head[st];i;i=next[i]) { int p=to[i]; if(p==fa[st] or p==son[st]) continue; dfs2(p,p); } } ii get_lca(int x,int y) { int fx=top[x],fy=top[y]; while(fx!=fy) { if(deep[x]<deep[y]) swap(x,y),swap(fx,fy); x=fa[fx],fx=top[x]; } return deep[x]<deep[y]?x:y; } signed main() { freopen("friendship.in","r",stdin),freopen("friendship.out","w",stdout); n=read(),m=read(); for(re i=1;i<=500000;i++) B[i]=J[i]=i; int opt,k,x; timi=n; for(re i=1;i<=m;i++) { opt=read(); if(opt==0) { opt=read(),k=read(); ++timi; if(opt==1) { for(re j=1;j<=k;j++) { x=read(); add(timi,x); in[x]=1; int fx=get_B(x); B[fx]=timi; if(k==1) J[get_J(x)]=timi; } } else { for(re j=1;j<=k;j++) { x=read(); add(timi,x); in[x]=1; int fx=get_J(x); J[fx]=timi; if(k==1) B[get_B(x)]=timi; } } } else cun[++cnt]=(node){read(),read()}; } for(re i=1;i<=timi;i++) if(!vis[i] and !in[i]) dfs(i,0,i),dfs2(i,i); for(re i=1;i<=cnt;i++) { int x=cun[i].x,y=cun[i].y; if(be[x]!=be[y] or be[x]==0 or be[y]==0) printf("0\n"); else { int lca=get_lca(x,y); if(lca==x) { int fx=get_J(x),fy=get_J(y); (fx==fy)?printf("1\n"):printf("0\n"); } else if(lca==y) { int fx=get_B(x),fy=get_B(y); (fx==fy)?printf("1\n"):printf("0\n"); } else printf("0\n"); } } return 0; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgfzwx.html