Cod sursa(job #2175404)

Utilizator dragomirmanuelDragomir Manuel dragomirmanuel Data 16 martie 2018 17:01:12
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include <bitset>

using namespace std;

const int NMax = 100005;
vector < int > G[NMax], Gt[NMax], cmp[NMax];
stack < int > st;
bitset < NMax > viz;
int N, M, ctc;

void DFS(int nod)
{
    viz[nod] = 1;

    for(auto it: G[nod])
    {
        if(!viz[it])
            DFS(it);
    }

    st.push(nod);
}

void DFSt(int nod)
{
    viz[nod] = 1;

    cmp[ctc].push_back(nod);

    for(auto it: Gt[nod])
    {
        if(!viz[it])
            DFSt(it);
    }

}

int main()
{
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);

    scanf("%d%d",&N,&M);
    for(int i=1; i<=M; ++i)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        G[x].push_back(y);
        Gt[y].push_back(x);
    }

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

    viz.reset();

    while(!st.empty())
    {
        if(!viz[st.top()])
        {
            ++ctc;
            DFSt(st.top());
        }

        st.pop();
    }

    cout << ctc << "\n";
    for(int i=1; i<=ctc; ++i)
    {
        for(int j=0; j<cmp[i].size(); ++j)
            cout << cmp[i][j] << " ";

        cout << "\n";
    }

    return 0;
}