Cod sursa(job #1782304)

Utilizator bogdan10bosBogdan Sitaru bogdan10bos Data 17 octombrie 2016 22:49:23
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;

#define FILE_IO

int N, M, K;
int f[100005];
int ord[100005];
vector <int> edg[100005], redg[100005];
vector <int> cmp;
vector < vector <int> > scc;

void DFS(int nod)
{
    if(f[nod])  return;
    f[nod] = 1;
    for(auto nxt: edg[nod])
        DFS(nxt);
    ord[++K] = nod;
}

void DFS1(int nod)
{
    if(f[nod] == 2) return;
    f[nod] = 2;
    cmp.push_back(nod);
    for(auto nxt: redg[nod])
        DFS1(nxt);
}

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

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

    for(int i = 1; i <= N; i++)
        DFS(i);

    for(int i = N; i >= 1; i--)
        if(f[ ord[i] ] != 2)
        {
            cmp.clear();
            DFS1(ord[i]);
            sort(cmp.begin(), cmp.end());
            scc.push_back(cmp);
        }

    printf("%d\n", scc.size());
    for(auto cmp: scc)
    {
        for(auto vtx: cmp)
            printf("%d ", vtx);
        printf("\n");
    }

    return 0;
}