Cod sursa(job #1346917)

Utilizator ArmandNMArmand Nicolicioiu ArmandNM Data 18 februarie 2015 17:58:28
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 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],aux,componente;
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);
    }

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

void DFSt(int nod)
{
    viz[nod] = false;
    sol[componente].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]])
        {
            componente++;
            DFSt(postordine[i]);
        }
    }

    g << componente << '\n';

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

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

    return 0;
}