Cod sursa(job #2357156)

Utilizator victorv88Veltan Victor victorv88 Data 27 februarie 2019 10:19:49
Problema Componente tare conexe Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

int n, m, from,k, to, in, llk[100005], ix[100005], viz[100005];
vector<int>graph[100005];
vector<int>rez[100005];
stack<int>s;

void conexe(int ind)
{
    ix[ind]=llk[ind]=in;
    ++in;
    s.push(ind);
    viz[ind]=1;
    for (auto &v:graph[ind])
    {
        if (ix[v]==0)
        {
            conexe(v);
            llk[ind]=min(llk[ind],llk[v]);
        }
        else if (viz[v]==1)
        {
            llk[ind]=min(llk[ind],llk[v]);
        }
    }
    if (ix[ind]==llk[ind])
    {
        while (!s.empty())
        {
            int el=s.top();
            s.pop();
            rez[k].push_back(el);
            viz[el]=0;
            if (ix[el]==llk[el])
            {
                k++;
                return;
            }
        }
    }
}

int main()
{
    f >> n >> m;
    for (int i=1; i<=m; ++i)
    {
        f >> from >> to;
        graph[from].push_back(to);
    }
    for (int i=1; i<=n;++i)
    {
        if (ix[i]==0)
        {
            conexe(i);
        }
    }
    g << k << '\n';
    for (int i=0; i<k; ++i)
    {
        for (auto &v:rez[i])
            g << v <<' ';
        g<<'\n';
    }
    return 0;
}