Cod sursa(job #2522289)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 12 ianuarie 2020 11:49:14
Problema Componente tare conexe Scor 94
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 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;
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;
    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();
        nr_comp ++;
        dfsGT(aux);
        while(viz2[a = stiva.top()] == true)
        {
            componente[nr_comp].push_back(stiva.top());
            stiva.pop();
            if(stiva.size() == 0)break;
        }
    }
    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;
}