Cod sursa(job #1919175)

Utilizator tudormaximTudor Maxim tudormaxim Data 9 martie 2017 18:14:06
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>
using namespace std;

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

const int maxn = 1e5 + 5;
vector <int> G[maxn], Ctc[maxn];
bitset <maxn> In_Stk;
int Low[maxn], Lev[maxn], Stk[maxn], top, comp, ind;

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

int main() {
    ios_base :: sync_with_stdio (false);
    int n, m, x, y, i, j;
    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) Dfs(i);
    }
    fout << comp << "\n";
    for (i = 1; i <= comp; i++) {
        sort(Ctc[i].begin(), Ctc[i].end());
        for (j = 0; j < (int) Ctc[i].size(); j++) {
            fout << Ctc[i][j] << " ";
        }
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}