Cod sursa(job #2113361)

Utilizator omegasFilip Ion omegas Data 24 ianuarie 2018 15:18:46
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

struct graf{
int nod;
int dist;
graf* next;
};

graf* v[100001];
int comp[100001];
int c=1;
int counter=0;

void add(int a, int b)
{
    graf* q = new graf;
    q->nod  = b;
    q->next = v[a];
    v[a] = q;
}

void DFS(int node){
    ++counter;
    comp[node] = c;
    graf *p;
    p=v[node];
    while(p!=NULL){
        if(comp[p->nod] != c)
            DFS(p->nod);
        p = p->next;
    }

}

int main()
{
    int i,x,y;
    int n,m;
    fin >> n >> m;
    for(i=1;i<=m;++i){
    fin >> x >> y;
    add(x,y);
    }
    i = 1;
    while(counter < n){
        if(comp[i] == 0)
            DFS(i),
            ++c;
        ++i;
    }
    cout << c - 1;

    return 0;
}