Cod sursa(job #2927462)

Utilizator teodorescunicolasteodorescu nicolas alexandru teodorescunicolas Data 20 octombrie 2022 17:23:02
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <stdio.h>
#include <string.h>
#include <vector>

#define NO_NODES 100000

using namespace std;

int noNodes;
bool marked[NO_NODES];

vector<int> graph[NO_NODES];
vector<int> revGraph[NO_NODES];
vector<int> stackOrder;
vector<int> components[NO_NODES];

void resetMarked() {
    memset( marked, false, sizeof(marked) );
}

void dfs( vector<int>* graph, vector<int>& visited, int node ) {
    marked[node] = true;

    for ( int neighbour : graph[node] )
        if ( !marked[neighbour] )
            dfs( graph, visited, neighbour );

    visited.push_back( node );
}
int main()
{
    FILE *fin, *fout;
    int n, m, i, x, y, noComponents;

    fin = fopen( "ctc.in", "r" );
    fout = fopen( "ctc.out", "w" );

    fscanf( fin, "%d%d", &n, &m );
    for ( i = 0; i < m; i++ ) {
        fscanf( fin, "%d%d", &x, &y );
        graph[x - 1].push_back( y - 1 );
        revGraph[y - 1].push_back( x - 1 );
    }

    for ( x = 0; x < n; ++x )
        if ( !marked[x] )
            dfs( graph, stackOrder, x );

    resetMarked();

    noComponents = 0;
    while ( stackOrder.size() ) {
        x = stackOrder.back();
        stackOrder.pop_back();

        if ( !marked[x] ) {
            dfs( revGraph, components[noComponents], x );
            noComponents++;
        }
    }

    for ( i = 0; i < noComponents; i++ ) {
        for ( int node : components[i] )
            fprintf( fout, "%d ", node + 1 );

        fputc( '\n', fout );
    }

    fclose( fin );
    fclose( fout );
    return 0;
}