G Operating on a Graph
并查集+链表
https://blog.csdn.net/Wen_Yongqi/article/details/107443575
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=8e5+10; 4 struct node 5 { 6 int v,nxt; 7 }G[maxn*2]; 8 int head[maxn]; int num; int last[maxn]; 9 int fa[maxn]; 10 void add(int u,int v) 11 { 12 G[++num].v=v;G[num].nxt=head[u];head[u]=num; 13 if(!last[u]) last[u]=num; 14 } 15 int Found(int x){return x==fa[x]?x:fa[x]=Found(fa[x]);} 16 int main() 17 { 18 int T; 19 scanf("%d",&T); 20 while(T--){ 21 num=0; 22 int n,m; 23 scanf("%d%d",&n,&m); 24 for(int i=0;i<=n;i++){ 25 fa[i]=i; 26 head[i]=last[i]=0; 27 } 28 for(int i=1;i<=m;i++){ 29 int u,v; 30 scanf("%d%d",&u,&v); 31 u++;v++; 32 add(u,v);add(v,u); 33 } 34 int op; 35 scanf("%d",&op); 36 while(op--) 37 { 38 int x; 39 scanf("%d",&x); 40 x++; 41 if(x!=Found(x))continue; 42 head[0]=last[0]=0; 43 for(int i=head[x];i;i=G[i].nxt) 44 { 45 int v=G[i].v; 46 int fv=Found(v); 47 if(fv==x)continue; 48 fa[fv]=x; 49 G[last[fv]].nxt=head[0]; 50 head[0]=head[fv]; 51 if(!last[0]) 52 last[0]=last[fv]; 53 } 54 head[x]=head[0]; 55 last[x]=last[0]; 56 } 57 for(int i=1;i<=n;i++) 58 printf("%d ",Found(i)-1); 59 printf("\n"); 60 } 61 }