Cod sursa(job #2372136)

Utilizator alexandra_paticaAndreea Alexandra Patica alexandra_patica Data 6 martie 2019 21:44:46
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <queue>
#include <vector>
#include <stack>
using namespace std;
ifstream f ("ctc.in");
ofstream g ("ctc.out");

int n, m, i, x, y, nr_componente, k, j;
int a[100002], b[100002];
vector<int>G[100002], C[100002],ctc[100002];
stack<int>s;

void dfs1(int x)
{
    a[x]=1;
    for (int i=0; i<G[x].size(); i++)
        if (!a[G[x][i]]) dfs1(G[x][i]);
    s.push(x);
}

void dfs2(int x)
{
    b[x]=nr_componente;
    for (int i=0; i<C[x].size(); i++)
        if (!b[C[x][i]]) dfs2(C[x][i]);
}

int main ()
{
    f >> n >> m;
    for (int i=1; i<=m; i++)
    {
        f >> x >> y;
        G[x].push_back(y);
        C[y].push_back(x);
    }

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

    while (!s.empty())
    {
        x=s.top();
        s.pop();
        if (!b[x])
        {
            nr_componente++;
            dfs2(x);
        }
    }

    for (int i=1; i<=n; i++)
        ctc[b[i]].push_back(i);

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