Cod sursa(job #1690252)

Utilizator tudormaximTudor Maxim tudormaxim Data 14 aprilie 2016 21:50:18
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>
using namespace std;

ifstream fin ("ctc.in");
ofstream fout ("ctc.out");

const int nmax = 1e5+5;
vector <int> g[nmax], ctc[nmax];
stack <int> st;
bitset <nmax> viz;
int lev[nmax], low[nmax], ind=1, nr;

void tarjan(int dad) {
    int nod;
    low[dad]=lev[dad]=ind++;
    st.push(dad);
    viz[dad]=true;
    for(auto son : g[dad]) {
        if(lev[son]==0) {
            tarjan(son);
            low[dad]=min(low[dad], low[son]);
        }
        else if(viz[son]==true) {
            low[dad]=min(low[dad], low[son]);
        }
    }
    if(low[dad]==lev[dad]) {
        nr++;
        do {
            nod=st.top();
            st.pop();
            viz[nod]=false;
            ctc[nr].push_back(nod);
        } while(nod!=dad);
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    int n, m, i, x, y;
    fin >> n >> m;
    for(i=1; i<=m; i++) {
        fin >> x >> y;
        g[x].push_back(y);
    }
    for(i=1; i<=n; i++)
        if(lev[i]==0) tarjan(i);

    fout << nr << "\n";
    for(i=1; i<=nr; i++) {
        for(auto it : ctc[i])
            fout << it << " ";
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}