Cod sursa(job #921717)

Utilizator Mihai22eMihai Ionut Enache Mihai22e Data 21 martie 2013 11:28:08
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

const int MAX_N = 100002;

int N, M, NrSCC, x, y, ind;
int index[MAX_N], lowlink[MAX_N], in_st[MAX_N];
vector < int > v[MAX_N], SCC[MAX_N];
stack < int > st;

inline void strong_connect(int x)
{
    ++ind;
    index[x] = lowlink[x] = ind;
    st.push(x), in_st[x] = 1;
    for(int i = 0; i < v[x].size(); ++i)
    {
        int y = v[x][i];
        if(!index[y])
        {
            strong_connect(y);
            lowlink[x] = min(lowlink[x], lowlink[y]);
        }
        else if(in_st[y])
            lowlink[x] = min(lowlink[x], index[y]);
    }

    if(index[x] == lowlink[x])
    {
        ++NrSCC;
        do
        {
            y = st.top(), st.pop();
            SCC[NrSCC].push_back(y);
            in_st[y] = 0;
        }while(y != x);
    }
}

int main()
{
    ifstream f("ctc.in");
    ofstream g("ctc.out");
    
    f >> N >> M;
    for(int i = 1; i <= M; ++i)
    {
        f >> x >> y;
        v[x].push_back(y);
    }

    for(int i = 1; i <= N; ++i)
        if(!index[i])
            strong_connect(i);
    
    g << NrSCC << '\n';
    for(int i = 1; i <= NrSCC; ++i)
    {
        for(int j = 0; j < SCC[i].size(); ++j)
            g << SCC[i][j] << " ";
        g << '\n';
    }

    f.close();
    g.close();

    return 0;
}