1. 程式人生 > >HRBUST - 1073 病毒

HRBUST - 1073 病毒

病毒
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;
}