[关闭]
@xiaoziyao 2020-03-26T13:50:22.000000Z 字数 1745 阅读 1180

Timus Online Judge(Ural)1671 Anansi's Cobweb题解

Timus


题目简述:4/3/4/4/并查集

传送门:1671. Anansi's Cobweb

题面

Usatiy-Polosatiy XIII decided to destroy Anansi's home — his cobweb. The cobweb consists of N nodes, some of which are connected by threads. Let us say that two nodes belong to the same piece if it is possible to get from one node to the other by threads. Usatiy-Polosatiy has already decided which threads and in what order he would tear and now wants to know the number of pieces in cobweb after each of his actions.

输入

The first line contains integers N and M — the number of nodes and threads in the cobweb, respectively(2 ≤ N ≤ 100000; 1 ≤ M ≤ 100000). Each of the next M lines contains two different integers — the 1-based indices of nodes connected by current thread. The threads are numbered from 1 to M in the order of description. Next line contains an integer Q which denotes the quantity of threads Usatiy-Polosatiy wants to tear (1 ≤ Q ≤ M). The last line contains numbers of these threads — different integers separated by spaces.

输出

Output Q integers — the number of pieces in Anansi's cobweb after each of Usatiy-Polosatiy's action. Separate numbers with single spaces.

样例

input1:
4 4
1 2
2 3
1 3
3 4
3
2 4 3
output1:
1 2 3
input2:
3 1
1 2
1
1
output2:
3

分析

题意:给定一个n()点m()边的图,给定q(1\leqslant q\leqslant q)次删边操作,求删后连通块的数量

离线,然后倒序并查集,这题比较套路

代码

  1. #include<stdio.h>
  2. const int maxn=100005;
  3. int i,j,k,m,n,q,now;
  4. int f[maxn],u[maxn],v[maxn],ban[maxn],ck[maxn],ans[maxn];
  5. int find(int x){
  6. return f[x]==x? x:f[x]=find(f[x]);
  7. }
  8. int main(){
  9. scanf("%d%d",&n,&m);
  10. for(i=1;i<=n;i++)
  11. f[i]=i;
  12. for(i=1;i<=m;i++)
  13. scanf("%d%d",&u[i],&v[i]);
  14. scanf("%d",&q);
  15. for(i=1;i<=q;i++){
  16. scanf("%d",&ban[i]);
  17. ck[ban[i]]=1;
  18. }
  19. now=n;
  20. for(i=1;i<=m;i++)
  21. if(ck[i]==0)
  22. if(find(u[i])!=find(v[i]))
  23. now--,f[find(u[i])]=find(v[i]);
  24. for(i=q;i>=1;i--){
  25. ans[i]=now;
  26. if(find(u[ban[i]])!=find(v[ban[i]]))
  27. now--,f[find(u[ban[i]])]=find(v[ban[i]]);
  28. }
  29. for(i=1;i<=q;i++)
  30. printf("%d%c",ans[i],i==q? '\n':' ');
  31. return 0;
  32. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注