Cod sursa(job #1690259)

Utilizator tudormaximTudor Maxim tudormaxim Data 14 aprilie 2016 22:00:28
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;

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

const int nmax = 1e5+5;
vector <int> g[nmax], gt[nmax], ctc[nmax];
bitset <nmax> viz;
int st[nmax], top, nr;

void sort_top(int dad) {
    viz[dad]=true;
    for(auto son : g[dad])
        if(viz[son]==false) sort_top(son);
    st[++top]=dad;
}

void dfs(int dad) {
    viz[dad]=true;
    ctc[nr].push_back(dad);
    for(auto son : gt[dad])
        if(viz[son]==false) dfs(son);
}

int main() {
    ios_base::sync_with_stdio(false);
    int n, m, i, x, y;
    fin >> n >> m;
    for(i=1; i<=m; i++) {
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    for(i=1; i<=n; i++)
        if(viz[i]==false) sort_top(i);
    viz=0;
    for(i=top; i; i--) {
        if(viz[st[i]]==false) {
            nr++;
            dfs(st[i]);
        }
    }
    fout << nr << "\n";
    for(i=1; i<=nr; i++) {
        for(auto it : ctc[i])
            fout << it << " ";
        fout << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}