Cod sursa(job #2509738)

Utilizator AndreiGSGhiurtu Andrei AndreiGS Data 14 decembrie 2019 17:57:37
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

int viz[100005], vizRev[100005];
int n, m;
vector<int> graph[100005], reversedGraph[100005], currCC;
vector<vector<int>> allCC;
stack<int> s;

void citire()
{
    int x, y;
    f>>n>>m;
    for(int i=0; i<m; i++)
    {
        f>>x>>y;
        graph[x].push_back(y);
        reversedGraph[y].push_back(x);
    }
}

void parcurgere(int x)
{
    viz[x]=1;
    for(auto &v : graph[x])
        if(viz[v]==0)
            parcurgere(v);
    s.push(x);
}

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

void parcurgereReversedGraph(int x)
{
    vizRev[x]=1;
    for(auto &v : reversedGraph[x])
        if(vizRev[v]==0)
            parcurgereReversedGraph(v);
    currCC.push_back(x);
}

void reversedDfs()
{
    while(!s.empty())
    {
        int nod=s.top();
        s.pop();
        if(vizRev[nod]==0)
        {
            parcurgereReversedGraph(nod);
            allCC.push_back(currCC);
            currCC.clear();
        }

    }
}

void afisare()
{
    g<<allCC.size()<<"\n";
    for(auto &p : allCC)
    {
        for(auto &nod : p)
            g<<nod<<" ";
        g<<"\n";
    }
}

int main()
{
    citire();
    dfs();
    reversedDfs();
    afisare();

    return 0;
}