Cod sursa(job #2974426)

Utilizator iProgramInCppiProgramInCpp iProgramInCpp Data 4 februarie 2023 09:21:47
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <list>
using namespace std;
ifstream fin ("ctc.in");
ofstream fout("ctc.out");
#define NMAX 100002
vector<int> G[NMAX];
int n, m;
int index[NMAX], lowlink[NMAX], onstack[NMAX];
stack<int> S;
list<vector<int>> ctc;
int cindex = 1;
void tareconex(int i)
{
    index[i] = cindex;
    lowlink[i] = cindex;
    cindex++;
    S.push(i);
    onstack[i] = 1;
    for (const int& x : G[i])
    {
        if (index[x] == 0)
        {
            tareconex(x);
            lowlink[i] = min(lowlink[i], lowlink[x]);
        }
        else if (onstack[x])
        {
            lowlink[i] = min(lowlink[i], index[x]);
        }
    }

    if (lowlink[i] == index[i])
    {
        vector<int> cc;
        int w = -1;
        do
        {
            w = S.top();
            S.pop();
            onstack[w] = false;
            cc.push_back(w);
        }
        while (w != i);
        sort(cc.begin(), cc.end());
        ctc.push_front(cc);
    }
}

void tarjan()
{
    for (int i=1; i<=n; i++)
    {
        if (index[i] == 0)
            tareconex(i);
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    fin>>n>>m;

    for (int i = 0; i < m; i++)
    {
        int a, b;
        fin >> a >> b;
        G[a].push_back(b);
    }

    tarjan();

    fout << ctc.size() << '\n';
    for (auto & cc : ctc)
    {
        for (auto & x : cc)
            fout << x << ' ';
        fout << '\n';
    }

    return 0;
}