Cod sursa(job #2765459)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 26 iulie 2021 22:52:46
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int MAX = 100001;

int n, m, id, scc;
int low[MAX], ids[MAX];
bool inStack[MAX];
vector <int> V[MAX], vec[MAX];
stack <int> S;

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

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

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

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

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

int main()
{
    Read();
    for (int i = 1; i <= n; i++)
    {
        if (ids[i] == 0)
        {
            DFS(i);
        }
    }
    Print();
}