Cod sursa(job #2120960)

Utilizator B_RazvanBaboiu Razvan B_Razvan Data 3 februarie 2018 10:21:19
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#define NMAX 100005

using namespace std;

int n, m, indexGlobal = 1, nrSol;
struct nodes
{
    int index, lowlink;
    bool onstack;
} v[NMAX];
vector <int> g[NMAX], sol[NMAX];
stack <int> s;

void read()
{
    scanf("%d%d", &n, &m);
    for(int i=1; i<=m; ++i)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        g[x].push_back(y);
    }
}

void dfs(int node)
{
    v[node].index = indexGlobal;
    v[node].lowlink = indexGlobal;
    indexGlobal++;
    s.push(node);
    v[node].onstack = true;
    vector <int>::iterator it;
    for(it = g[node].begin(); it != g[node].end(); ++it)
        if(v[*it].index == 0)
        {
            dfs(*it);
            v[node].lowlink = min(v[node].lowlink, v[*it].lowlink);
        }
        else if(v[*it].onstack == true)
            v[node].lowlink = min(v[node].lowlink, v[*it].index);

    if(v[node].index == v[node].lowlink)
    {
        while(s.top()!=node)
        {
            v[s.top()].onstack = false;
            sol[nrSol].push_back(s.top());
            s.pop();
        }
        sol[nrSol].push_back(node);
        s.pop();
        v[node].onstack=false;
        nrSol++;
    }
}

void solve()
{
    for(int i=1; i<=n; ++i)
        if(v[i].index == 0)
            dfs(i);
    printf("%d\n", nrSol);
    vector <int>::iterator it;
    for(int i=0; i<nrSol; ++i)
    {
        for(it = sol[i].begin(); it != sol[i].end(); ++it)
            printf("%d ", *it);
        printf("\n");
    }
}

int main()
{
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);
    read();
    solve();
    return 0;
}