Cod sursa(job #2024930)

Utilizator andreistanStan Andrei andreistan Data 21 septembrie 2017 17:00:07
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
using namespace std;

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

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

int N, M, nr, nrc;
bool viz[100001];
int postordine[100001];

nod *v1[100001], *v2[100001], *cc[100001];

void add(nod *&dest, int val)
{
    nod *p;
    p = new nod;
    p -> x = val;
    p -> leg = dest;
    dest = p;
}

void citiregraf()
{
    f >> N >> M;
    while(M--)
    {
        int x, y;
        f >> x >> y;
        add(v1[x], y);
        add(v2[y], x);
    }
}

void DFS(int vf)
{
    viz[vf] = 1;
    for(nod *p = v1[vf]; p != NULL; p = p -> leg)
        if(viz[p -> x] == 0)
            DFS(p -> x);
    postordine[++nr] = vf;
}

void DFSt(int vf)
{
    viz[vf] = 0;
    add(cc[nrc], vf);
    for(nod *p = v2[vf]; p != NULL; p = p -> leg)
        if(viz[p -> x] == 1)
            DFSt(p -> x);
}
void componente()
{
    int i;
    for(i = 1; i <= N; i++)
        if(viz[i] == 0)
            DFS(i);
    for(i = N; i >= 1; i--)
        if(viz[postordine[i]] == 1)
        {
            nrc++;
            DFSt(postordine[i]);
        }
}

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

int main()
{
    citiregraf();
    componente();
    afis();
    return 0;
}