Cod sursa(job #2669825)

Utilizator StefanaArinaStefana Arina Tabusca StefanaArina Data 8 noiembrie 2020 02:54:42
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
#include<vector>
#include<stack>

using namespace std;

#define NMAX 100005

bool viz1[NMAX], viz2[NMAX];
vector <int> graph1[NMAX];
vector <int> graph2[NMAX];
vector <int> comp[NMAX];
stack <int> ord;
int n, m, ncomp;

ifstream f("ctc.in");
ofstream g("ctc.out");

 
void dfs1(int nod)
{
    viz1[nod] = 1;
    int len, i, var;
    len = graph1[nod].size();
    
    for(i = 0; i < len; i++)
    {
        var = graph1[nod][i];
        if(!viz1[var])
            dfs1(var);
    }
    ord.push(nod);
}
 
void dfs2(int nod)
{
    viz2[nod] = 1;
    int len, i, var;
    len = graph2[nod].size();
    
    for(i = 0; i < len; i++)
    {
        var = graph2[nod][i];
            if(!viz2[var])
                dfs2(var);
    }
    comp[ncomp].push_back(nod);
}
 
int main()
{
    int i, j, x, y, len;
    f >> n >> m;
    
    for(i = 0; i < m; i++)
    {
        f >> x >> y;
        graph1[x].push_back(y);
        graph2[y].push_back(x);
    }
    
    for(i = 1; i <= n; i++)
        if(viz1[i] == 0)
            dfs1(i);
            
    while(!ord.empty())
    {
        x = ord.top();
        ord.pop();
        if(!viz2[x])
        {
            dfs2(x);
            ncomp++;
        }
    }
    
    g << ncomp << endl;
    
    for(i = 0; i < ncomp; i++)
    {
        len = comp[i].size();
        
        for(j = 0; j < len; j++)
            g << comp[i][j] << ' ';
            
        g << '\n';
    }
    return 0;
}