Cod sursa(job #2224849)

Utilizator stefan.botezStefan Botez stefan.botez Data 25 iulie 2018 13:10:24
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <bitset>

using namespace std;

const int nmax = 100005;

int n, m, x, y, i, cnt, stiva[nmax];
vector<int> g[nmax], gt[nmax], comp[nmax];
bitset<nmax> viz;

void dfs(int x)
{
    viz[x] = 1;
    for(auto it : g[x])
        if(!viz[it])
            dfs(it);
    stiva[++cnt] = x;
}

void dfst(int x)
{
    comp[cnt].push_back(x);
    viz[x] = 1;
    for(auto it : gt[x])
        if(!viz[it])
            dfst(it);
}

int main()
{
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(; m; m--)
    {
        scanf("%d%d", &x, &y);
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    for(i = 1; i <= n; i++)
        if(!viz[i])
            dfs(i);
    viz = 0;
    cnt = 0;
    for(i = n; i; i--)
    {
        x = stiva[i];
        if(!viz[x])
            cnt++, dfst(x);
    }
    printf("%d\n", cnt);
    for(i = 1; i <= cnt; i++)
    {
        for(auto it : comp[i])
            printf("%d ", it);
        printf("\n");
    }
    return 0;
}