Cod sursa(job #2471453)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 10 octombrie 2019 22:32:58
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

vector<int> graf[MAXN], rev[MAXN], ctc;
vector<vector<int> >ans;
stack<int> stk;
bool viz[MAXN];

void dfs(int nod, int dir){
    if(viz[nod]) return;
    viz[nod] = 1;
    if(!dir){
        for(auto x:graf[nod]) dfs(x, 0);
        stk.push(nod);
    }
    else{
        for(auto x:rev[nod]) dfs(x, 1);
        ctc.push_back(nod);
    }
}

int main()
{
    ifstream fin("ctc.in");
    ofstream fout("ctc.out");
    int n, m;
    fin >> n >> m;
    while(m){
        int x, y;
        fin >> x >> y;
        graf[x].push_back(y);
        rev[y].push_back(x);
        m--;
    }
    for(int i = 1; i <= n; ++i)
        if(!viz[i]) dfs(i, 0);
    memset(viz, 0, sizeof(viz));
    while(!stk.empty()){
        int nod = stk.top();
        stk.pop();
        if(!viz[nod]){
            dfs(nod, 1);
            ans.push_back(ctc);
            ctc.clear();
        }
    }
    fout << ans.size() << "\n";
    for(auto x:ans){
        for(auto y:x) fout << y << " ";
        fout << "\n";
    }
    return 0;
}