Cod sursa(job #1799584)

Utilizator radu.leonardoThe Doctor radu.leonardo Data 6 noiembrie 2016 15:30:08
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <cstdio>
#define buff_size 20000000

char buff[buff_size];int pos;
int i,n,m,v[100001],x,y,aux,sz[100001],nr=0;
FILE*f=freopen("dfs.in","r",stdin);
FILE*g=freopen("dfs.out","w",stdout);

inline void read(int &nr)
{
    while(buff[pos] < '0' || buff[pos] > '9') if(++pos == buff_size) fread(buff,  buff_size,1, stdin), pos = 0;
    nr = 0;
    while('0' <= buff[pos] && buff[pos] <= '9')
    {
        nr = nr * 10 + buff[pos] - '0';
        if(++pos == buff_size) fread(buff, 1, buff_size, stdin), pos = 0;
    }
}

int main()
{   fread(buff,  buff_size,1, stdin);
    read(n);read(m);
    for(i=1; i<=n; i++)   v[i]=i,sz[i]=1;
    for(i=1;i<=m;i++)
    {read(x);read(y);
     while(x!=v[x]) aux=v[v[x]],v[x]=aux,x=aux;
     while(y!=v[y]) aux=v[v[y]],v[y]=aux,y=aux;
     if(x!=y){
            nr++;
            if(sz[x]<sz[y]) v[x]=y,sz[y]+=sz[x];
            else v[y]=x,sz[x]+=sz[y];
        }
    }
    printf("%d\n" ,n-nr);
}