Cod sursa(job #2195416)

Utilizator MoldovanAndrei1Moldovan Andrei MoldovanAndrei1 Data 16 aprilie 2018 13:02:31
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <cstdio>
using namespace std;
int t[100005],h[100005];
int findset(int x)
{
    while(t[x]!=x)x=t[x];
    return x;
}
void unionset(int x,int y)
{
           if(h[x]>h[y])
            t[y]=x;
           if(h[y]>h[x])
            t[x]=y;
    if(h[x]==h[y])
       {
            h[x]++;
    t[y]=x;
       }

}
int main()
{
    freopen("dfs.in","r",stdin);
    freopen("dfs.out","w",stdout);
    int n , m ,x , y,i;
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)t[i]=i,h[i]=1;
    for(i=1;i<=m;i++)
    {
        scanf("%d%d",&x,&y);
        int l1=findset(x),l2=findset(y);
        if(l1!=l2)
            unionset(l1,l2);
    }

int cnt=0;
for(i=1;i<=n;i++)
        if(t[i]==i)cnt++;
printf("%d\n",cnt);
return 0;
}