Cod sursa(job #2641393)

Utilizator AndreiAlexandru2k3Ciucan Andrei Alexandru AndreiAlexandru2k3 Data 11 august 2020 11:47:10
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
using namespace std;

const int NMAX = 100000;

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

nod *G[NMAX + 1],
    *GT[NMAX + 1],
    *CTC[NMAX + 1];

int N, M, nrc,
    nr, post[NMAX + 1];

bool viz[NMAX + 1];

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

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;
    for(int i = 1; i <= M; i++)
    {
        int x, y;
        f >> x >> y;
        add(G[x], y);
        add(GT[y], x);
    }
}

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;
}

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() ///Al Kosaraju Sharir
{
    int i;
    for(int i = 1; i <= N; i++)
        if(!viz[i])
            DFS(i);
    //
    for(int i = N; i >= 1; i--)
        if(viz[post[i]] == 1)
        {
            nrc++;
            DFST(post[i]);
        }
}

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;
}