Cod sursa(job #2924728)

Utilizator lucianul31Moisii Lucian lucianul31 Data 9 octombrie 2022 16:31:43
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int NMAX = 1.0e5 + 5;
bool Belonging[NMAX], Seen[NMAX];
vector < int > Edges[NMAX];
vector < vector < int > > Components;
stack < int > Q;
int NodeLevel[NMAX], RootLevel[NMAX], nrCMP = -1, Level, N, M;

void Tarjan(int x)
{
    Level++;
    NodeLevel[x] = RootLevel[x] = Level;
    Seen[x] = 1;
    Belonging[x] = 1;
    Q.push(x);
    for(int newX : Edges[x])
    {
        if(!Seen[newX])
        {
            Tarjan(newX);
            RootLevel[x] = min(RootLevel[x], RootLevel[newX]);
        }
        else
        {
            if(Belonging[newX])
                RootLevel[x] = min(RootLevel[x], RootLevel[newX]);
        }
    }
    if(NodeLevel[x] == RootLevel[x])
    {
        int Node;
        nrCMP++;
        Components.push_back(vector < int > ());
        do
        {
            Node = Q.top();
            Q.pop();
            Components[nrCMP].push_back(Node);
            Belonging[Node] = 0;
        } while (Node != x);
    }
}

int main()
{
    int x, y;
    in >> N >> M;
    for(int i = 1; i <= M; i++)
    {
        in >> x >> y;
        Edges[x].push_back(y);
    }
    for(int i = 1; i <= N; i++)
    {
        if(!Seen[i])
        {   
            Level = 0;
            Tarjan(i);
        }
    }
    for(vector < int > it : Components)
    {   
        for(int x : it)
            out << x << ' ';
        out << '\n';
    }
    return 0;
}