Cod sursa(job #2975995)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 7 februarie 2023 22:44:07
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream f ("ctc.in");
ofstream g ("ctc.out");

const int SIZE = 100005;

int n, m, id, cnt;
int ids[SIZE], low[SIZE];

bool inStack[SIZE];

vector <int> adj[SIZE];
vector <int> ssc[SIZE];

stack <int> s;

void Read()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        f >> x >> y;
        adj[x].push_back(y);
    }
}

void Tarjan(int node)
{
    s.push(node);
    inStack[node] = true;
    low[node] = ids[node] = ++id;

    for (int i = 0; i < adj[node].size(); i++)
    {
        int neighbour = adj[node][i];
        if (ids[neighbour] == 0)
        {
            Tarjan(neighbour);
        }
        if (inStack[neighbour] == true)
        {
            low[node] = min(low[node], low[neighbour]);
        }
    }

    if (low[node] == ids[node])
    {
        cnt++;
        int n = 0;
        while (n != node)
        {
            n = s.top();
            s.pop();
            inStack[n] = false;
            ssc[cnt].push_back(n);
        }
    }
}

void Print()
{
    g << cnt << "\n";
    for (int i = 1; i <= cnt; i++)
    {
        for (unsigned int j = 0; j < ssc[i].size(); j++)
        {
            g << ssc[i][j] << " ";
        }
        g << "\n";
    }
}

int main()
{
    Read();

    for (int i = 1; i <= n; i++)
    {
        if (ids[i] == 0)
        {
            Tarjan(i);
        }
    }

    Print();

    return 0;
}