1671. Anansi's Cobweb(并查集)
并查集 对于询问删除边之后的连通块 可以倒着加边 最后再倒序输出
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 using namespace std; 7 #define N 100010 8 int p[N],father[N],a,b,f[N]; 9 int pp[N]; 10 struct node 11 { 12 int x,y; 13 }ed[N]; 14 int find(int x) 15 { 16 if(father[x]!=x) 17 father[x] = find(father[x]); 18 return father[x]; 19 } 20 void add(int a,int b) 21 { 22 int x = find(a); 23 int y = find(b); 24 if(x!=y) 25 father[x] = y; 26 } 27 int main() 28 { 29 int i,n,m,q; 30 while(scanf("%d%d",&n,&m)!=EOF) 31 { 32 memset(f,0,sizeof(f)); 33 for(i =1; i <= n ; i++) 34 father[i] = i; 35 for(i = 1; i <= m ; i++) 36 { 37 scanf("%d%d",&ed[i].x,&ed[i].y); 38 } 39 scanf("%d",&q); 40 for(i = 1; i <= q ;i++) 41 { 42 scanf("%d",&p[i]); 43 f[p[i]] = 1; 44 } 45 for(i = 1; i <= m ; i++) 46 { 47 if(!f[i]) 48 add(ed[i].x,ed[i].y); 49 } 50 int num = 0; 51 for(i = 1; i <= n ; i++) 52 if(father[i]==i) 53 num++; 54 pp[1] = num; 55 int o = 1; 56 for(i = q ; i>1 ; i--) 57 { 58 int x = find(ed[p[i]].x); 59 int y = find(ed[p[i]].y); 60 if(x==y) 61 { 62 pp[++o] = num; 63 continue; 64 } 65 else 66 { 67 father[x] = y; 68 num--; 69 pp[++o] = num; 70 } 71 } 72 for(i = o ; i > 1 ; i--) 73 printf("%d ",pp[i]); 74 printf("%d\n",pp[1]); 75 } 76 return 0; 77 }