Cod sursa(job #2477440)

Utilizator andreitudorpAndrei Tudor Popescu andreitudorp Data 20 octombrie 2019 13:06:38
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

#define MAXN 100005

ifstream cin("ctc.in");
ofstream cout("ctc.out");

int nr = 0;

stack<int> s;
vector<int> g[MAXN], g1[MAXN], ctc[MAXN];

int ok[MAXN];

void DFS1(int Nod)
{
    ok[Nod] = 1;

    for(int i = 0; i < g[Nod].size(); i++)
    {
        int Vecin = g[Nod][i];

        if(!ok[Vecin])
            DFS1(Vecin);
    }
    s.push(Nod);
}

void DFS2(int Nod)
{
    ok[Nod] = 2;
    ctc[nr].push_back(Nod);

    for(int i = 0; i < g1[Nod].size(); i++)
    {
        int Vecin = g1[Nod][i];

        if(ok[Vecin]==1)
            DFS2(Vecin);
    }
}

int main()
{
    int n, m;
    cin >> n >> m;
    int x, y;

    for(int i = 1; i <= m; i++)
    {
        cin >> x >> y;
        g[x].push_back(y);
        g1[y].push_back(x);
    }

    for(int i = 1; i <= n; i++)
        if(!ok[i])
            DFS1(i);

    while(!s.empty())
    {
        int Nod = s.top();

        if (ok[Nod] == 1)
        {
            nr++;
            DFS2(Nod);
        }

        s.pop();
    }

    cout << nr <<"\n";

    for(int i = 1; i <= nr; i++)
    {
        for(int j = 0; j < ctc[i].size(); j++)
            cout << ctc[i][j] <<" ";
        cout << "\n";
    }
}