Cod sursa(job #2024849)

Utilizator laraamy16Cioc Amelia laraamy16 Data 21 septembrie 2017 12:28:18
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
using namespace std;
int n, m, viz[100005], postordine[100001], nr, cnt;
ofstream g("ctc.out");
struct nod
{
    int x;
    nod *leg;
};
nod *v[100001], *vt[100001], *c[100001];


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

void citire()
{
    ifstream f("ctc.in");
    f >> n >> m;
    int i, x, y;
    for(i = 1; i <= m; i++)
    {
        f >> x >> y;
        add(v[x], y);
        add(vt[y], x);
    }
    f.close();
}

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

void DFST(int vf)
{
    nod *p;
    viz[vf] = 0;
    add(c[cnt], vf);
    for(p = vt[vf]; p != NULL; p = p -> leg)
        if(viz[p -> x]) DFST(p -> x);
}

int main()
{
    citire();
    for(int i = 1; i <= n; i++)
        if(!viz[i])
            DFS(i);
    for(int i = n; i >= 1; i--)
        if(viz[postordine[i]])
        {
            cnt++;
            DFST(postordine[i]);
        }
    g << cnt << '\n';
    for(int i = 1; i <= cnt; i++)
    {
        for(nod *p = c[i]; p != NULL; p = p->leg)
            g << p->x << ' ';
        g << '\n';
    }
    return 0;
}