Cod sursa(job #1535302)

Utilizator c0mradec0mrade c0mrade Data 24 noiembrie 2015 16:28:55
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include<fstream>
using namespace std;
ifstream in("dfs.in");
ofstream out("dfs.out");
int n,m,x,y,nr,viz[100001];

typedef struct nod{
    int x;
    nod *next;
}*node;

node v[100001];

void add(node &urm, int value)
{
    node p;
    p = new nod;
    p->x=value;
    p->next=urm;
    urm=p;
}

void read()
{
    in>>n>>m;
    for(int i=0;i<m;i++)
    {
        in>>x>>y;
        add(v[x],y);
        add(v[y],x);
    }
    in.close();
}

void dfs(int nod)
{
    node p;
    viz[nod]=1;
    for(p=v[nod];p!=NULL;p=p->next)
        if(!viz[p->x])
            dfs(p->x);
}

void exec()
{
    for(int i=1;i<=n;i++)
        if(!viz[i])
        {
            nr++;
            dfs(i);
        }
}

void print()
{
    out<<nr<<'\n';
    out.close();
}

int main(){
    read();
    exec();
    print();
    return 0;
}