Cod sursa(job #1411684)

Utilizator ArmandNMArmand Nicolicioiu ArmandNM Data 31 martie 2015 21:23:19
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>

const int NMAX = 100005;

using namespace std;

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

int N,M;
int postordine[NMAX];
vector <int> v[NMAX];
vector <int> w[NMAX];
vector <int> sols[NMAX];
bool viz[NMAX];
int aux,x,y,nrComponente;

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);
    }
    postordine[++aux] = nod;
}

void DFSt(int nod)
{
    sols[nrComponente].push_back(nod);
    viz[nod] = true;
    for (int i = 0; i < w[nod].size(); ++i)
    {
        int vecin = w[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);
        w[y].push_back(x);
    }

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

    for (int i = 1; i <= N; ++i)
        viz[i] = false;

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

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

    f.close();
    g.close();
    return 0;
}