Cod sursa(job #1171038)

Utilizator SelonyEcho Slam Selony Data 15 aprilie 2014 00:12:29
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <vector>
 
using namespace std;
 
const char InFile[] = "ctc.in";
const char OutFile[] = "ctc.out";
const int MaxN = 100111;
 
ifstream fin(InFile);
ofstream fout(OutFile);
 
int N, M, x, y, low[MaxN], niv[MaxN], S[MaxN], index, inS[MaxN];
vector<int> G[MaxN], comp;
vector< vector<int> > sol;
 
void Tarjan(int nod)
{
    niv[nod] = low[nod] = ++index;
    S[++S[0]] = nod;
    inS[nod] = 1;
    for (vector<int>::iterator it = G[nod].begin(); it != G[nod].end(); ++it)
    {
        if (!niv[*it])
        {
            Tarjan(*it);
        }
        if (inS[*it])
        {
            if (low[nod] > low[*it])
            {
                low[nod] = low[*it];
            }
        }
    }
 
    if (low[nod] == niv[nod])
    {
        comp.clear();
        do
        {
            inS[S[S[0]]] = 0;
            comp.push_back(S[S[0]]);
            --S[0];
        } while (S[S[0]+1] != nod);
        sol.push_back(comp);
    }
}
 
int main()
{
    fin >> N >> M;
    for (register int i = 1; i <= M; ++i)
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
    fin.close();
 
    for (register int i = 1; i <= N; ++i)
    {
        if (!niv[i])
        {
            Tarjan(i);
        }
    }
 
    fout << sol.size() << "\n";
    for (vector< vector<int> >::iterator it = sol.begin(); it != sol.end(); ++it)
    {
        for (vector<int>::iterator elIt = it->begin(); elIt != it->end(); ++elIt)
        {
            fout << *elIt << " ";
        }
        fout << "\n";
    }
    fout.close();
    return 0;
}