HRBUST - 1073 病毒

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41657943/article/details/84798139
病毒
Time Limit: 1000 MS Memory Limit: 65536 K
Total Submit: 3484(839 users) Total Accepted: 1170(732 users) Rating:  Special Judge: No
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

题目链接: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;
}

猜你喜欢

转载自blog.csdn.net/qq_41657943/article/details/84798139