病毒 | ||||||
| ||||||
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),分别表示人数和接触关系数量; | ||||||
Output | ||||||
输出数据仅包含一个整数,为共需隔离的人数(包含0号在内)。 | ||||||
Sample Input | ||||||
100 4 | ||||||
Sample Output | ||||||
3 |
题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1073
这道题也是并查集应用
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
int fa[50002],a,b,m,n;
void build(int qwq)
{
for(int i=1;i<=qwq;i++)
fa[i]=i;
return ;
}
int find(const int &x) //找祖先
{
return fa[x]==x?x:fa[x]=find(fa[x]);
}
bool che(const int &x,const int &y) //判断祖先是不是一样
{
return find(x)==find(y);
}
void mer(const int &x,const int &y) //合并
{
if(!che(x,y))
fa[fa[x]]=fa[y];
return ;
}
int main()
{
int i,t=0;
scanf("%d%d",&n,&m);
build(n);
for(i=1;i<=m;i++)
scanf("%d%d",&a,&b),
mer(a,b);
for(i=0;i<n;i++)
{
if(che(0,i)) //判断谁和0同一祖先,同一祖先就说明他俩有关系都需要隔离
t++;
}
printf("%d\n",t);
return 0;
}