Cod sursa(job #2543447)

Utilizator KappaClausUrsu Ianis Vlad KappaClaus Data 11 februarie 2020 10:14:40
Problema Componente tare conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
#define NMAX 100000 + 1
using namespace std;

vector<vector<int>> graph(NMAX, vector<int>());
int N, M;
stack<int> node_stack;
bool viz[NMAX];
bool onStack[NMAX];

int id[NMAX], low[NMAX], counter = 0;

vector<vector<int>> ctcs;

void dfs(int node)
{
    id[node] = low[node] = ++counter;
    viz[node] = onStack[node] = true;

    node_stack.push(node);

    for(auto& next : graph[node])
    {
        if(viz[next] == false)
            dfs(next);


        if(onStack[node] == true)
            low[node] = min(low[node], low[next]);
    }

    if(low[node] == id[node])
    {
        vector<int> ctc;
        int x;
        do {
            x = node_stack.top();
            node_stack.pop();
            onStack[x] = false;
            ctc.push_back(x);

        }while(x != node);


        ctcs.push_back(ctc);
    }
}

int main()
{
    ifstream fin("ctc.in");
    ofstream fout("ctc.out");

    fin >> N >> M;

    for(int i = 1; i <= M; ++i){
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }

    for(int i = 1; i <= N; ++i)
    {
        if(viz[i] == false)
            dfs(i);
    }

    fout << ctcs.size() << '\n';

    for(auto& ctc : ctcs){
        for(auto& node : ctc)
            fout << node << ' ';

        fout << '\n';
    }
}