Cod sursa(job #1344452)

Utilizator ArmandNMArmand Nicolicioiu ArmandNM Data 16 februarie 2015 19:00:57
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>

const int NMAX = 100005;

using namespace std;

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

int N,M,x,y,postordine[NMAX],nr,nrsol;
vector <int> v[NMAX];
vector <int> vt[NMAX];
vector <int> sol[NMAX];
bool viz[NMAX];

void DFS(int nod)
{
    viz[nod] = true;
    for (int i = 0; i < v[nod].size(); ++i)
    {
        int vecin = v[nod][i];
        if (!viz[vecin])
            DFS(vecin);
    }

    nr++;
    postordine[nr] = nod;
}

void DFSt(int nod)
{
    viz[nod] = false;
    sol[nrsol].push_back(nod);

    for (int i = 0; i < vt[nod].size(); ++i)
    {
        int vecin = vt[nod][i];
        if (viz[vecin])
            DFSt(vecin);
    }
}

int main()
{
    f >> N >> M;

    for (int i = 1; i <= M; ++i)
    {
        f >> x >> y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }

    for (int i = 1; i <= N; ++i)
    {
        if (!viz[i])
            DFS(i);
    }

    for (int i = N; i >= 1; --i)
    {
        if (viz[ postordine[i] ])
        {
            ++nrsol;
            DFSt(postordine[i]);
        }
    }

    g << nrsol << '\n';

    for (int i = 1; i <= nrsol; ++i)
    {
        for (int j = 0; j < sol[i].size(); ++j)
        {
            g << sol[i][j] << " ";
        }
        g << '\n';
    }

    f.close();
    g.close();

    return 0;
}