Cod sursa(job #2842454)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 31 ianuarie 2022 20:23:46
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;
int nr_comp;
stack<int> Stack;
vector <int> comp[100005];
vector <int> G[100005];
vector <int> GT[100005];
int viz[100005];
void DFS(int x)
{
    viz[x] = 1;
    for(int i = 0; i < G[x].size(); i ++)
    {
        int nod = G[x][i];
        if(viz[nod] == 0)
            DFS(nod);
    }
    Stack.push(x);
}
void DFS_T(int x)
{
    viz[x] = nr_comp;
    for(int i = 0; i < GT[x].size(); i ++)
    {
        int nod = GT[x][i];
        if(viz[nod] == 0)
            DFS_T(nod);
    }
}
int i, j, n, m, x, y, 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] == 0)
            DFS(i);
    memset(viz, 0, sizeof(viz));
    while(!Stack.empty())
    {
        int aux = Stack.top();
        if(viz[aux] == 0)
        {
            nr_comp ++;
            DFS_T(aux);
        }
        Stack.pop();
    }
    for(i = 1; i <= n; i ++)
        comp[viz[i]].push_back(i);
    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;
}