Cod sursa(job #1480473)

Utilizator retrogradLucian Bicsi retrograd Data 2 septembrie 2015 17:23:43
Problema Componente tare conexe Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

#define MAXN 100005

vector<int> G[MAXN], Gt[MAXN];
unordered_set<int> Viz1, Viz2;
int ctc;

int In[MAXN];
vector<int> Nodes[MAXN];

void dfs1(int node) {
    Viz1.insert(node);
    for(auto vec : G[node])
        if(Viz1.find(vec) == Viz1.end())
            dfs1(vec);
}

void dfs2(int node) {
    if(Viz1.find(node) != Viz1.end()) {
        In[node] = ctc;
        Nodes[ctc].push_back(node);
    }

    Viz2.insert(node);
    for(auto vec : Gt[node])
        if(Viz2.find(vec) == Viz2.end())
            dfs2(vec);
}



int main() {

    //#ifndef ONLINE_JUDGE
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);
    //#endif

    int n, m, a, b;
    cin>>n>>m;

    while(m--) {
        cin>>a>>b;
        G[a].push_back(b);
        Gt[b].push_back(a);
    }

    for(int i=1; i<=n; i++) {
        if(!In[i]) {
            ctc++;

            dfs1(i);
            dfs2(i);

            Viz1.clear();
            Viz2.clear();

        }
    }

    cout<<ctc<<'\n';
    for(int i=1; i<=ctc; i++) {
        for(auto node : Nodes[i]) cout<<node<<" ";
        cout<<'\n';
    }

    return 0;
}