Cod sursa(job #1882336)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 17 februarie 2017 09:36:48
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;

constexpr int maxn = 1e5 + 10;

void stivuieste(const vector<int> vec[maxn], const int cur, bitset<maxn>& viz,
        vector<int>& st){
    viz[cur] = 1;
    for(const auto next : vec[cur])
        if(!viz[next])
            stivuieste(vec, next, viz, st);
    st.push_back(cur); }

vector<vector<int>> build_ctcs(const int n, const vector<int> vec[maxn]){
    static vector<int> inv_vec[maxn] = {};
    for(int i = 0; i < n; ++i)
        for(const auto j : vec[i])
            inv_vec[j].push_back(i);
    vector<vector<int>> rez;
    vector<int> st;
    bitset<maxn> viz = 0;
    for(int i = 0; i < n; ++i)
        if(!viz[i]) stivuieste(vec, i, viz, st);
    viz = 0;
    while(!st.empty()){
        if(!viz[st.back()]){
            rez.emplace_back(0, 0);
            stivuieste(inv_vec, st.back(), viz, rez.back()); }
        st.pop_back(); }
    return rez; }

ifstream f("ctc.in");
ofstream g("ctc.out");
int n, m;
vector<int> vec[maxn];

int main(){
    f >> n >> m;
    for(int i = 0, x, y; i < m; ++i){
        f >> x >> y;
        vec[x-1].push_back(y-1); }
    auto rez = build_ctcs(n, vec);
    g << rez.size() << '\n';
    for(const auto& x : rez){
        for(const auto y : x) g << y+1 << ' ';
        g << '\n'; }
    return 0; }