Cod sursa(job #2349926)

Utilizator DavidLDavid Lauran DavidL Data 20 februarie 2019 20:46:24
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fi("ctc.in");
ofstream fo("ctc.out");

const int NMAX = 1e5 + 5;

int n, m;
vector <int> G[NMAX], H[NMAX];
int stiva[NMAX], k;
vector <int> parte[NMAX];
int luat[NMAX];
bool viz[NMAX];
int nrComp;

void dfs1(int nod)
{
    viz[nod] = 1;
    //stiva[++k] = nod;

    for (auto v: G[nod])
    {
        if (!viz[v])
        {
            dfs1(v);
        }
    }
    stiva[++k] = nod;
}

void dfs2(int nod)
{
    luat[nod] = nrComp;
    parte[nrComp].push_back(nod);

    for (auto v: H[nod])
    {
        if (!luat[v])
        {
            dfs2(v);
        }
    }
}

int main()
{
    fi >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int u, v;
        fi >> u >> v;
        G[u].push_back(v);
        H[v].push_back(u);
    }

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

    //for (int i = 1; i <= k / 2; i++)
        //swap(stiva[i], stiva[k - i + 1]);

    while (k > 0)
    {
        while (k > 0 && luat[stiva[k]])
        {
            k--;
        }

        if (k == 0)
            break;

        int nod = stiva[k];

        nrComp++;
        dfs2(nod);
    }

    fo << nrComp << "\n";
    for (int i = 1; i <= nrComp; i++)
    {
        for (auto x: parte[i])
            fo << x << " ";
        fo << "\n";
    }

    return 0;
}