Cod sursa(job #2238415)

Utilizator AndreiVisoiuAndrei Visoiu AndreiVisoiu Data 5 septembrie 2018 16:39:08
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <cstdio>
#include <vector>

using namespace std;

const int NMAX = 100001;

vector<int> a[NMAX];
bool viz[NMAX];
int n;

struct nod
{
    int x;
    nod *urm;
};
nod *v[NMAX];

void add(nod *&p, int x) {
    nod *q = new nod;
    q->x = x;
    q->urm = NULL;
    if(p == NULL)
        p = q;
    else {
        nod *r = p;
        while(r->urm != NULL)
            r = r->urm;
        r->urm = q;
    }
}

void dfs(int x) {
    viz[x] = 1;
    nod *p;
    for(p = v[x]; p != NULL; p = p->urm)
        if(!viz[p->x]) dfs(p->x);
}
int main()
{
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);
    int m, x, y, comp = 0;
    scanf("%i %i", &n, &m);

    while(m--) {
        scanf("%i %i", &x, &y);
        add(v[x], y);
        add(v[y], x);
    }

    for(int i = 1; i <= n; i++)
        if(!viz[i]) {
            comp++;
            dfs(i);
        }
    printf("%i", comp);
    return 0;
}