Cod sursa(job #1373702)

Utilizator oprea1si2si3Oprea Sebastian oprea1si2si3 Data 4 martie 2015 20:12:38
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>
#include <vector>
using namespace std;

const int kNMax = 100010;
int n, sol;
vector<int> G[kNMax];
bool viz[kNMax];

void Citire() {
    ifstream in("dfs.in");
    int x, y, m;
    in >> n >> m;
    for (int i = 1; i <= m; ++i) {
        in >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    in.close();
}

void Dfs(int nod) {
    int vecin;
    viz[nod] = 1;
    for (int i = 0; i < G[nod].size(); ++i) {
        vecin = G[nod][i];
        if(!viz[vecin])
            Dfs(vecin);
    }
}

void Solve() {
    for (int i = 1; i <= n; ++i)
        if (!viz[i]) {
            ++sol;
            Dfs(i);
        }
}

void Afisare() {
    ofstream out("dfs.out");
    out << sol << '\n';
    out.close();
}

int main() {
    Citire();
    Solve();
    Afisare();
    return 0;
}