Cod sursa(job #1826870)

Utilizator tudormaximTudor Maxim tudormaxim Data 10 decembrie 2016 23:39:48
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>
using namespace std;

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

const int maxn = 1e5 + 5;
vector <int> G[maxn];
vector <int> Ctc[maxn];
bitset <maxn> Vis;
stack <int> Stk;
int Low[maxn], Lev[maxn], ind, ans;

void Tarjan(int node) {
    vector <int> :: iterator it;
    int val;
    Lev[node] = Low[node] = ++ind;
    Vis[node] = true;
    Stk.push(node);
    for (it = G[node].begin(); it != G[node].end(); it++) {
        if (Lev[*it] == 0) {
            Tarjan(*it);
            Low[node] = min(Low[node], Low[*it]);
        } else if (Vis[*it] == true) {
            Low[node] = min(Low[node], Low[*it]);
        }
    }
    if (Lev[node] == Low[node]) {
        ans++;
        do {
            val = Stk.top();
            Ctc[ans].push_back(val);
            Vis[val] = false;
            Stk.pop();
        } while (val != node);
    }
}

int main() {
    ios_base :: sync_with_stdio (false);
    vector <int> :: iterator it;
    int n, m, x, y, i;
    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 << ans << "\n";
    for (i = 1; i <= ans; i++) {
        for (it = Ctc[i].begin(); it != Ctc[i].end(); it++) {
            fout << *it <<  " ";
        }
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}