Cod sursa(job #2398303)

Utilizator DimaTCDima Trubca DimaTC Data 5 aprilie 2019 12:00:45
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include<bits/stdc++.h>
#define N 100030
using namespace std;


int n,m,t,k;
vector<int>V[N],CTC[N];
int disc[N], low[N];
bool inS[N];
stack<int>S;

void DFS(int x) {
    disc[x]=low[x]=++t;
    inS[x]=1; S.push(x);
    for (auto it:V[x]) {
        if (!disc[it]) {
            DFS(it);
            low[x]=min(low[x],low[it]);
        } else if (inS[it]) {
            low[x]=min(low[x], disc[it]);
        }
    }

    if (low[x]==disc[x]) {
        int y; ++k;
        do {
            y=S.top(); S.pop();
            inS[y]=0;
            CTC[k].push_back(y);
        } while (y!=x);
    }
}

int main() {
    ifstream cin("ctc.in");
    ofstream cout("ctc.out");
    cin>>n>>m;
    for (int i=1; i<=m; ++i) {
        int x,y; cin>>x>>y;
        V[x].push_back(y);
    }
    for (int i=1; i<=n; ++i) {
        if (!disc[i]) DFS(i);
    }

    cout<<k<<'\n';
    for (int i=1; i<=k; ++i) {
        for (auto it:CTC[i]) cout<<it<<" "; cout<<'\n';
    }

    return 0;
}