Cod sursa(job #1087717)

Utilizator mihai995mihai995 mihai995 Data 19 ianuarie 2014 19:29:40
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>
using namespace std;

const int N = 1 + 1e5;

vector<int> graph[N];
bool use[N];

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

void dfs(int x){
    use[x] = true;
    int n = graph[x].size();
    for (size_t i = 0 ; i < n ; i++)
        if (!use[ graph[x][i] ])
            dfs( graph[x][i] );
}

int main(){
    int n, m, x, y, ans = 0;

    in >> n >> m;

    while (m--){
        in >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    for (int i = 1 ; i <= n ; i++)
        if (!use[i]){
            dfs(i);
            ans++;
        }
    out << ans << "\n";
    return 0;

}