Cod sursa(job #2046192)

Utilizator LucaSeriSeritan Luca LucaSeri Data 23 octombrie 2017 15:51:33
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;
const int maxn = 100010;

vector<int> ctc[maxn];
vector<int> gr1[maxn];
vector<int> gr2[maxn];
bool viz[maxn];
vector<int> v;

ifstream f("ctc.in");
ofstream g("ctc.out");

int cnt = 0;
void dfs1(int node){
    viz[node] = 1;
    for(auto x : gr1[node]){
        if(viz[x] == 0){
            dfs1(x);
        }
    }

    v.push_back(node);
}

void dfs2(int node){
    ctc[cnt].push_back(node);
    viz[node] = 0;
    for(auto x : gr2[node]){
        if(viz[x]){
            dfs2(x);
        }
    }
}
int main(){
    int n, m;
    f >> n >> m;
    for(int i = 0; i < m; ++i){
        int a, b;
        f >> a >> b;
        gr1[a].push_back(b);
        gr2[b].push_back(a);
    }

    for(int i = 1; i <= n; ++i){
        if(!viz[i]){
            dfs1(i);
        }
    }

    reverse(v.begin(), v.end());
    for(auto x : v){
        if(viz[x]){
            ++cnt;
            dfs2(x);
        }
    }
    g << cnt << '\n';
    for(int i = 1; i <= cnt; ++i){
        for(auto x : ctc[i]){
            g << x << ' ';
        }
        g << '\n';
    }
    return 0;
}