Cod sursa(job #2663165)

Utilizator YetoAdrian Tonica Yeto Data 25 octombrie 2020 14:55:57
Problema Parcurgere DFS - componente conexe Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <stack>
#include <vector>
using namespace std;
int n, m, x, y, i, j, nr;
vector <int> g[100001];
stack <int> s;
bool viz[100001];

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

void dfs() 
{
    int x = 0;
    for (int i = 0; i < n; i++) {
        if (!viz[i]) {
            nr ++;
            s.push(i);
            while (!s.empty()) {
                x = s.top();
                s.pop();
                if (!viz[x]) {
                    viz[x] = 1;
                    for (int j = 0; j < g[x].size(); j++) {
                        s.push(g[x][j]);
                    }
                }
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    dfs();
    fout << nr;

    return 0;
}