Cod sursa(job #2045033)

Utilizator nurof3nCioc Alex-Andrei nurof3n Data 21 octombrie 2017 18:37:13
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
using namespace std;

ofstream g ("ctc.out");
const int MAXN = 100005;
int n, m, niv[MAXN], minniv[MAXN], st[MAXN], vf, nr, cnt;
bool viz[MAXN];

struct nod
{
    int x;
    nod *leg;
};
nod *v[MAXN], *c[MAXN];


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);
    }
    f.close();
}

void tarjan (int u)
{
    niv[u] = minniv[u] = nr;
    nr++;
    st[++vf] = u;
    viz[u] = true;

    nod *p;
    for (p = v[u]; p != NULL; p = p -> leg)
        if (niv[p->x] == -1)
        {
            tarjan (p->x);
            minniv[u] = min (minniv[u], minniv[p->x]);
        }
        else if (viz[p->x])
            minniv[u] = min (minniv[u], niv[p->x]);

    if (minniv[u] == niv[u])
    {
        cnt++;
        do
        {
            add (c[cnt], st[vf]);
            viz[st[vf]] = false;
            vf--;
        }
        while (u != st[vf + 1]);
    }
}

int main()
{
    citire();
    for (int i = 1; i <= n; i++) niv[i] = -1;
    nr = vf = 0;
    for (int i = 1; i <= n; i++)
        if (niv[i] == -1)
            tarjan (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;
}