Cod sursa(job #1971277)

Utilizator GinguIonutGinguIonut GinguIonut Data 20 aprilie 2017 08:48:55
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <algorithm>

#define nMax 100001
#define pb push_back

using namespace std;

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

int n, m, ind, nrctc;
int lev[nMax], low[nMax], viz[nMax];
vector<int> stck, ctc[nMax], G[nMax];

void tarjan(int node)
{
    lev[node]=low[node]=++ind;
    viz[node]=1;
    stck.pb(node);

    for(vector<int>::iterator it=G[node].begin(); it!=G[node].end(); it++)
    {
        int fiu=*it;
        if(lev[fiu]==0)
        {
            tarjan(fiu);
            low[node]=min(low[node], low[fiu]);
        }
        else
            if(viz[fiu])
                low[node]=min(low[node], low[fiu]);
    }
    if(low[node]==lev[node])
    {
        nrctc++;
        int nodeAux;
        do
        {
            nodeAux=stck.back();
            viz[nodeAux]=0;
            ctc[nrctc].pb(nodeAux);
            stck.pop_back();
        }
        while(node!=nodeAux);
    }

}

int main()
{
    int a, b;
    fin>>n>>m;
    for(int i=1; i<=m; i++)
    {
        fin>>a>>b;
        G[a].pb(b);
    }

    for(int i=1; i<=n; i++)
        if(lev[i]==0)
            tarjan(i);

    fout<<nrctc<<'\n';
    for(int i=1; i<=nrctc; i++)
    {
        for(vector<int>::iterator it=ctc[i].begin(); it!=ctc[i].end(); it++)
            fout<<*it<<" ";
        fout<<'\n';
    }
}