Cod sursa(job #986606)

Utilizator BlackLordFMI Alex Oprea BlackLord Data 19 august 2013 11:57:15
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
int n, m, x, y, i, nr, v[100010];

struct nod{
    int v;
    nod *n;
};
nod *p[100010];
nod *q;

void dfs(int x){
    v[x]=1;
    for(nod *q=p[x]; q; q=q->n)
        if(v[q->v]==0)
            dfs(q->v);
}

int main(){
    f>>n>>m;
    for(i=1; i<=n; i++)
        p[i]=NULL;
    for(i=1; i<=m; i++)
    {
        f>>x>>y;
        q=new nod;
        q->n=p[x];
        q->v=y;
        p[x]=q;
        q=new nod;
        q->n=p[y];
        q->v=x;
        p[y]=q;
    }
    f.close();
    for(i=1; i<=n; i++)
        if(v[i]==0)
        {
            nr++;
            dfs(i);
        }
    g<<nr<<"\n";
    g.close();
    return 0;
}