Cod sursa(job #2473126)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 13 octombrie 2019 13:24:16
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
#define N_MAX 100001
using namespace std;

vector<vector<int>> ctc, graph(N_MAX, vector<int>());
stack<int> st;
bool onStack[N_MAX], visited[N_MAX];
int id[N_MAX], low[N_MAX], n, m;

int t = 0;

void dfs(int node)
{
    st.push(node);
    onStack[node] = visited[node] = true;
    id[node] = low[node] = ++t;

    for(auto& next : graph[node])
    {
        if(!visited[next]) dfs(next);

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

    if(low[node] == id[node])
    {
        ctc.push_back(vector<int>());

        while(st.top() != node)
        {
            ctc.back().push_back(st.top());
            onStack[st.top()] = false;
            st.pop();
        }

        ctc.back().push_back(node);
        onStack[node] = false;
        st.pop();
    }
}


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

    fin >> n >> m;

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


    for(int i = 1; i <= n; ++i)
        if(!visited[i]) dfs(i);


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

    for(auto& c : ctc)
    {
        for(auto& node : c) fout << node << ' ';
        fout << '\n';
    }

}