Cod sursa(job #3126795)

Utilizator alexandra.calota02Alexandra Maria Calota alexandra.calota02 Data 6 mai 2023 23:31:06
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>
using namespace std;

class Task {
public:
    void solve() {
        read_input();
        print_output(get_result());
    }

private:
    static constexpr int NMAX = (int)1e5 + 5;

    int n, m;

    vector<int> adj[NMAX];

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

    void DFS_RECURSIVE(int node, vector<int> &p, int timestamp,
                       vector<int> &start, vector<int> &finish) {
        start[node] = ++timestamp;
 
        for (int neigh : adj[node]) {
            if (p[neigh] == -1) {
                p[neigh] = node;
                DFS_RECURSIVE(neigh, p, timestamp, start, finish);
            }
        }
 
        finish[node] = ++timestamp;
    }

    int get_result() {

        vector <int> p (n + 1);
        vector<int> start (n + 1);
        vector<int> finish (n + 1);
    
        for (int i = 1; i <= n; i++) {
            p[i] = -1;
        }

        int timestamp = 0;
        int components = 0;
    
        for (int i = 1; i <= n; i++ ) {
            if (p[i] == -1) {
                components++;
                DFS_RECURSIVE(i, p, timestamp, start, finish);
            }
        }
        return components;
    }


    void print_output(int components) {
        ofstream fout("dfs.out");
        fout << components;
        fout.close();
    }
};

int main() {
    auto* task = new (nothrow) Task();
    if (!task) {
        cerr << "new failed: WTF are you doing? Throw your PC!\n";
        return -1;
    }
    task->solve();
    delete task;
    return 0;
}