Cod sursa(job #1087716)

Utilizator mihai995mihai995 mihai995 Data 19 ianuarie 2014 19:28:41
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.72 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;
    vector<int> :: iterator end = graph[x].end();
    for (vector<int> :: iterator it = graph[x].begin() ; it != end ; it++)
        if (!use[ *it ])
            dfs( *it );
}

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;

}