Cod sursa(job #3036668)

Utilizator AndreiDeltaBalanici Andrei Daniel AndreiDelta Data 24 martie 2023 19:55:01
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
typedef long long ll;
typedef pair<int, int> pi;
int t, T;

int elapsed_time = 0;

void DFS(int node, vector<vector<int>>& edges, vector<int>& visited,
    vector<int>& start, vector<int>& end, vector<int>& father) {
    start[node] = elapsed_time;
    visited[node] = 1;
    for (int neigh : edges[node]) {
        if (!visited[neigh]) {
            elapsed_time = elapsed_time + 1;
            father[neigh] = node;
            DFS(neigh, edges, visited, start, end, father);
        }
    }
    visited[node] = 2;
    end[node] = elapsed_time;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n, m;
    f >> n >> m;
    vector<vector<int>> V(n + 1);

    for (int i = 0; i < m; i++) {
        int a, b;
        f >> a >> b;
        V[a].push_back(b);
    }

    int no_conex_component = 0;
    vector<int> visited(n + 1, 0);
    vector<int> start(n + 1, 0), end(n + 1, 0), father(n + 1, -1);
    for (int i = 1; i <= n; i++)
        if (!visited[i]) {
            DFS(i, V, visited, start, end, father);
            no_conex_component++;
        }

    g << no_conex_component << '\n';

    return 0;
}