Cod sursa(job #2522297)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 12 ianuarie 2020 11:57:17
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>
using namespace std;
int n, m, i, j, x, y, nr_comp, a;
vector <int> G[100005];     //graful implicit
vector <int> GT[100005];    //graful transpus
vector <int> componente[100005];
stack <int> stiva;
stack <int> stiva2;
bool viz1[100005], viz2[100005];
void dfsG(int x)
{
    viz1[x] = true;
    for(int i = 0; i < G[x].size();i ++)
    {
        int aux = G[x][i];
        if(viz1[aux] == false)dfsG(aux);
    }
    stiva.push(x);
}
void dfsGT(int x)
{
    viz2[x] = true;
    stiva2.push(x);
    for(int i = 0; i < GT[x].size(); i ++)
    {
        int aux = GT[x][i];
        if(viz2[aux] == false)dfsGT(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(viz1[i] == false)dfsG(i);
    while(!stiva.empty())
    {
        int aux = stiva.top();
        if(viz2[aux] == false)
        {
            nr_comp ++;
            dfsGT(aux);
            while(!stiva2.empty())
            {
                componente[nr_comp].push_back(stiva2.top());
                stiva2.pop();
            }
        }
        stiva.pop();
    }
    g << nr_comp << "\n";
    for(i = 1; i <= nr_comp; i ++)
    {
        for(j = 0; j < componente[i].size(); j ++)
            g << componente[i][j] << " ";
        g << "\n";
    }
    return 0;
}