Cod sursa(job #1116200)

Utilizator dragos-giidragos ghinoiu dragos-gii Data 22 februarie 2014 13:37:13
Problema Parcurgere DFS - componente conexe Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#define nmax 50006

using namespace std;

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

struct graf
{
    int nod;
    graf *next;
}*L[nmax];

int N, M;
int viz[nmax];

void add (int from, int to)
{
    graf *q = new graf;

    q -> nod = to;
    q -> next = L[from];
    L[from] = q;
}

void read()
{
    int x, y;

    fin >> N >> M;

    for (int i = 1; i <= M; ++i)
    {
        fin >> x >> y;
        add(x, y);
        add(y, x);
    }
}

void DFS(int x)
{
    graf *q = L[x];

    viz[x] = 1;

    while (q != NULL && viz[q -> nod] == 0)
    {
        DFS(q -> nod);
        q = q -> next;
    }
}

int main()
{
    int cnt = 0, i;

    read();

    for (i = 1; i <= N; ++i)
        if (viz[i] == 0)
        {
            ++cnt;
            DFS(i);
        }

    fout << cnt;

    return 0;
}