Cod sursa(job #2358423)

Utilizator IOI_MDA_003Sebastian Chicu IOI_MDA_003 Data 28 februarie 2019 08:49:06
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;

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

const int N_MAX = 100000 + 5;

int n, m;

bitset<N_MAX> viz1, viz2;
stack<int> st;
vector<vector<int> > ans;
vector<int> vec[N_MAX], rvec[N_MAX];

void dfs1(int nod){
    if(viz1[nod])
        return;
    viz1[nod] = true;
    for(auto v : vec[nod])
        if(!viz1[v])
            dfs1(v);
    st.push(nod);
}

vector<int> temp;

void dfs2(int nod){
    if(viz2[nod])
        return;
    viz2[nod] = true;
    temp.push_back(nod);
    for(auto v : rvec[nod]){
        if(!viz2[v])
            dfs2(v);
    }
}

int main()
{
    fin >> n >> m;
    while(m--){
        int a, b;
        fin >> a >> b;
        vec[a].push_back(b);
        rvec[b].push_back(a);
    }

    for(int i = 1; i <=n; ++i)
        dfs1(i);

    while(!st.empty()){
        if(!viz2[st.top()]){
            while(temp.size())
                temp.pop_back();
            dfs2(st.top());
            ans.push_back(temp);
        }
        st.pop();
    }

    fout << ans.size() << "\n";

    for(auto v : ans){
        for(auto i : v)
            fout << i << " ";
        fout << "\n";
    }

    return 0;
}