哈理工oj (acm.hrbust.edu.cn) 1073病毒
| 病毒 | ||||||
|
||||||
| Description | ||||||
|
某种病毒袭击了某地区,该地区有N(1≤N≤50000)人,分别编号为0,1,...,N-1,现在0号已被确诊,所有0的直接朋友和间接朋友都要被隔离。例如:0与1是直接朋友,1与2是直接朋友,则0、2就是间接朋友,那么0、1、2都须被隔离。现在,已查明有M(1≤M≤10000)个直接朋友关系。如:0,2就表示0,2是直接朋友关系。 请你编程计算,有多少人要被隔离。 |
||||||
| Input | ||||||
|
第一行包含两个正整数N(1≤N≤50000),M(1≤M≤100000),分别表示人数和接触关系数量; 在接下来的M行中,每行表示一次接触,; 每行包括两个整数U, V(0 <= U, V < N)表示一个直接朋友关系。 |
||||||
| Output | ||||||
|
输出数据仅包含一个整数,为共需隔离的人数(包含0号在内)。 |
||||||
| Sample Input | ||||||
|
100 4 0 1 1 2 3 4 4 5 |
||||||
| Sample Output | ||||||
|
3 |
代码:
#include<stdio.h> int father[50010]; int find(int a)//查找元素,Find(x)返回元素x所在的集合的编号 { if(father[a] != a ) father[a] = find(father[a]); return father[a]; } int st(int x,int y)//将x与y所在的集合合并 { int fx,fy; fx = find(x); fy = find(y); if(fx != fy) father[fy] = fx; } int main() { int n,m; int u,v; int i,j,sum; int a,b; while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<50010;i++)//并查集的初始化,把每个点所在集合初始化为其自身。 father[i] = i; while(m--) { scanf("%d%d",&a,&b); st(a,b); } sum=0; int f0 = find(0); for(i=0;i<n;i++)//并查集的查找 { if(find(i)==f0) sum++; } printf("%d\n",sum); } return 0; }


浙公网安备 33010602011771号