Cod sursa(job #2842447)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 31 ianuarie 2022 20:10:37
Problema Componente tare conexe Scor 94
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>
using namespace std;
stack<int> Stack;
vector <int> comp[100005];
vector <int> G[100005];
vector <int> GT[100005];
bool viz[100005];
void DFS(int x)
{
    viz[x] = true;
    for(int i = 0; i < G[x].size(); i ++)
    {
        int nod = G[x][i];
        if(viz[nod] == false)
            DFS(nod);
    }
    Stack.push(x);
}
void DFS_T(int x)
{
    viz[x] = true;
    for(int i = 0; i < GT[x].size(); i ++)
    {
        int nod = GT[x][i];
        if(viz[nod] == false)
            DFS_T(nod);
    }
}
int i, j, n, m, x, y, nr_comp, aux;
int main()
{
    ifstream f("ctc.in");
    ofstream g("ctc.out");
    f >> n >> m;
    for(i = 1; i <= m; i ++)
    {
        f >> x >> y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
    for(i = 1; i <= n; i ++)
        if(viz[i] == false)
            DFS(i);
    memset(viz, false, sizeof(viz));
    while(!Stack.empty())
    {
        nr_comp ++;
        x = Stack.top();
        Stack.pop();
        comp[nr_comp].push_back(x);
        DFS_T(x);
        while(!Stack.empty())
        {
            aux = Stack.top();
            if(viz[aux] == true)
            {
                comp[nr_comp].push_back(aux);
                Stack.pop();
            }
            else
            {
                break;
            }
        }
    }
    g << nr_comp << "\n";
    for(i = 1; i <= nr_comp; i ++)
    {
        for(j = 0; j < comp[i].size(); j ++)
            g << comp[i][j] << " ";
        g << "\n";
    }
    return 0;
}