Cod sursa(job #2614328)

Utilizator AlexandruConstantinMazilu Alexandru AlexandruConstantin Data 11 mai 2020 16:55:14
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int NMAX = 100000;

struct nod
{
    int x;
    nod * next;
};

///  G - lista vecinilor nodului i in graful initial
/// GT - lista vecinilor nodului i in graful transpus

nod *G[NMAX +1], *GT[NMAX +1], *CTC[NMAX +1];
int N, M, nrc, nr, post[NMAX + 1];

bool viz[NMAX + 1];

void add(nod *&cap_lst, int nod_ad)
{
    nod *p;
    p = new nod;
    p -> x = nod_ad;
    p -> next = cap_lst;
    cap_lst = p;
}

void citireGraf()
{
    f >> N >> M;
    while(M--)
    {
        int x, y;
        f >> x >> y;
        add(G[x], y);  /// Adaugare arc (x, y) in graful G
        add(GT[y], x); /// Adaugare arc (y, x) in graful GT
    }
}

void DFS(int vf)
{
    viz[vf] = 1;
    for(nod *p = G[vf]; p != NULL; p = p -> next)
        if(viz[p -> x] == 0)
            DFS(p -> x);
    post[++nr] = vf; /// se memoreaza ordinea de parcurgere a nodurilor
}

void DFSt(int vf)
{
    viz[vf] = 0;
    add(CTC[nrc], vf); /// Nodul vf se adauga la CTC curenta
    for(nod *p = GT[vf]; p != NULL; p = p -> next)
        if(viz[p -> x] == 1)
            DFSt(p -> x);
}

void componente()
{
    int i;
    for(i = 1; i <= N; i++)
        if(viz[i] == 0)
            DFS(i);            /// DFS pe graful initial
    //
    for(i = N; i >= 1; i--)    /// Se parcurg nodurile in post ordine
        if(viz[post[i]] == 1)  /// Nodul post[i] nu a fost plasat intr-o CTC
        {
            nrc++;
            DFSt(post[i]);     /// DFS pe graful transpus
        }
}

void afis()
{
    g << nrc << '\n';
    for(int i = 1; i <= nrc; i++)
    {
        for(nod *p = CTC[i]; p != NULL; p = p -> next)
            g << p -> x << ' ';
        g << '\n';
    }
}

int main()
{

    citireGraf();
    componente();
    afis();
    return 0;
}