Cod sursa(job #728884)

Utilizator sana1987Laurentiu Dascalu sana1987 Data 29 martie 2012 08:30:06
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <vector>
#include <queue>
#include <cstdio>
#define N 100001

using namespace std;
vector<int> graph[N];
bool visited[N];
int n;

void dfs(int node) {
    visited[node] = true;

    for (vector<int>::iterator it = graph[node].begin();
        it != graph[node].end();
        it++) {
        if (!visited[*it])
            dfs(*it);
    }
}

int main() {
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);

    int m;
    scanf("%d %d", &n, &m);

    for (int i = 0; i < n; i++) {
        visited[i] = false;
    }

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

    int counter = 0;

    while (1) {
        bool find = false;
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                dfs(i);
                counter++;
            }
        }
        if (!find)
            break;
    }

    printf("%d\n", counter);

    return 0;
}