Cod sursa(job #2465980)

Utilizator LeVladzCiuperceanu Vlad LeVladz Data 1 octombrie 2019 10:07:02
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <vector>
#include <stack>
#define DIM 100005

using namespace std;

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

int n,m,i,j,x,y,index,cnt,v[DIM],low[DIM];
bool fs[DIM];
vector<int> L[DIM],ctc[DIM];
stack<int> s;

void dfs(int nod)
{
    index++; v[nod] = index; low[nod] = index;
    s.push(nod); fs[nod] = true;
    for (int i=0; i<L[nod].size(); i++)
    {
        int vecin = L[nod][i];
        if (!v[vecin])
        {
            dfs(vecin);
            low[nod] = min(low[nod], low[vecin]);
        }
        else
            if (fs[vecin])
                low[nod] = min(low[nod], v[vecin]);
    }
    if (v[nod] == low[nod])
    {
        cnt++; int vecin = 0;
        do {
            vecin = s.top(); s.pop();
            fs[vecin] = false;
            ctc[cnt].push_back(vecin);
        } while (vecin != nod);
    }
}

int main()
{
    fin >> n >> m;
    for (i=1; i<=m; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
    }
    for (i=1; i<=n; i++)
        if (!v[i])
            dfs(i);
    fout << cnt << "\n";
    for (i=1; i<=cnt; i++)
    {
        for (j=0; j<ctc[i].size(); j++)
            fout << ctc[i][j] << " ";
        fout << "\n";
    }
    return 0;
}