Cod sursa(job #652509)

Utilizator rootsroots1 roots Data 24 decembrie 2011 19:46:01
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>

#define gL 100001
#define useL 100001

using namespace std;

ifstream in;
ofstream out;

struct graf
{
    int nod;
    graf *link;
}*g[gL];

int use[useL];

inline void add_edge(int x,int y)
{
    graf *p=new graf;
    p->nod=y;
    p->link=g[x];
    g[x]=p;
}

inline void DFS(int nod)
{
    use[nod]=1;
    for(graf *p=g[nod];p;p=p->link)
        if(!use[p->nod]) DFS(p->nod);
}

int main()
{
    int M,N,cnt=0,x,y;

    in.open("dfs.in");

    in>>N>>M;
    for(;M--;)
    {
        in>>x>>y;
        add_edge(x,y);
        add_edge(y,x);
    }

    in.close();

    for(int i=1;i<=N;++i)
        if(!use[i]) DFS(i),++cnt;

    out.open("dfs.out");

    out<<cnt<<'\n';

    out.close();

    return 0;
}