Cod sursa(job #2189430)

Utilizator FrequeAlex Iordachescu Freque Data 28 martie 2018 12:09:11
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <stack>

using namespace std;

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

const int NMAX = 1e5 + 5;

vector <int> graph[NMAX];
vector <int> ans[NMAX];
stack <int> s;
int n, m, timp, cnt;
int disc[NMAX], low[NMAX];
bool vis[NMAX];

void dfs(int node)
{
    disc[node] = low[node] = ++timp;
    s.push(node);
    vis[node] = true;

    for (int next: graph[node])
    {
        if (disc[next] == -1)
        {
            dfs(next);
            low[node] = min(low[node], low[next]);
        }
        else if (vis[next])
            low[node] = min(low[node], disc[next]);
    }

    int topper;
    if (low[node] == disc[node])
    {
        ++cnt;
        while (s.top() != node)
        {
            topper = s.top();
            s.pop();
            ans[cnt].push_back(topper);
            vis[topper] = false;
        }
        topper = s.top();
        s.pop();
        ans[cnt].push_back(topper);
        vis[topper] = false;
    }
}

void write()
{
    cout << cnt << '\n';
    for (int i = 1; i <= cnt; ++i)
    {
        for (int j: ans[i])
            cout << j << " ";
        cout << "\n";
    }
}

void read()
{
    int x, y;

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

    memset(disc, -1, sizeof(disc));
    memset(low, -1, sizeof(low));
}

int main()
{
    read();

    for (int i = 1; i <= n; ++i)
        if (disc[i] == -1)
            dfs(i);

    write();

    return 0;
}