Cod sursa(job #1091502)

Utilizator cernat.catallinFMI Cernat Catalin Stefan cernat.catallin Data 25 ianuarie 2014 19:14:47
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include <stdio.h>
#include <vector>
using namespace std;

#define Nmax 100005

vector <int> graph[Nmax];
int n, m, c;
int visited[Nmax];

void read()
{
    int x, y;
    freopen("dfs.in", "r", stdin);

    scanf("%d %d", &n, &m);
    for (int i = 0; i < m; ++i){
        scanf("%d %d", &x, &y);
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    fclose(stdin);
}

void dfs(int node)
{
    vector <int>::iterator it;
    visited[node] = 1;

    for (it = graph[node].begin(); it != graph[node].end(); ++it)
        if (!visited[*it])
            dfs(*it);
}

int main()
{
    read();
    for (int i = 1; i <= n; ++i)
        if (!visited[i]){
            ++c;
            dfs(i);
        }
    freopen("dfs.out", "w", stdout);
    printf("%d\n", c);

    return 0;
}