Cod sursa(job #2813525)

Utilizator As932Stanciu Andreea As932 Data 6 decembrie 2021 21:11:45
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 100005;

int n, m, nr_comp;
bool vis[nmax];
vector <int> v[nmax], t[nmax], rsp[nmax];
stack <int> st;

void read(){
    fin >> n >> m;

    for(int i = 1; i <= m; i++){
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
        t[y].push_back(x);
    }
}

void dfs1(int x){
    vis[x] = true;

    for(auto y:v[x])
        if(!vis[y])
            dfs1(y);

    st.push(x);
}

void dfs2(int x){
    rsp[nr_comp].push_back(x);
    vis[x] = true;

    for(auto y:t[x])
        if(!vis[y])
            dfs2(y);
}

void solve(){
    for(int i = 1; i <= n; i++)
        if(!vis[i])
            dfs1(i);

    memset(vis, 0, sizeof(vis));

    while(!st.empty()){
        int nod = st.top();
        st.pop();

        if(!vis[nod]){
            nr_comp++;
            dfs2(nod);
        }
    }
}

void print(){
    fout << nr_comp << "\n";

    for(int i = 1; i <= nr_comp; i++){
        for(auto nod:rsp[i])
            fout << nod << " ";
        fout << "\n";
    }
}

int main()
{
    read();
    solve();
    print();

    return 0;
}