Cod sursa(job #3153672)

Utilizator andreea_chivuAndreea Chivu andreea_chivu Data 30 septembrie 2023 16:30:13
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const int NMAX = 100001;

vector <int> succesori[NMAX];
vector <int> predecesori[NMAX];
bool viz[NMAX];
vector <int> v;
vector <vector <int>> ctc;
int n;

void dfs(int x){
    viz[x] = true;
    v.push_back(x);
    for(auto y: succesori[x])
        if(!viz[y])
            dfs(y);
}

void dfs_t(int x){
    viz[x] = true;
    ctc[ctc.size() - 1].push_back(x);
    for(auto y: predecesori[x])
        if(!viz[y])
            dfs_t(y);
}

void reseteaza(){
    for(int i = 1; i <= n; i++){
        viz[i] = 0;
    }
}

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

    int m;
    fin >> n >> m;

    for(int i = 0; i < m; i++){
        int x, y;
        fin >> x >> y;
        succesori[x].push_back(y);
        predecesori[y].push_back(x);
    }

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

    reverse(v.begin(), v.end());
    reseteaza();

    for(auto x: v){
        if(!viz[x]){
            vector <int> comp;
            ctc.push_back(comp);
            dfs_t(x);
        }
    }

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

    for(auto c: ctc){
        for(auto x: c){
            fout << x << " ";
        }
        fout << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}