Cod sursa(job #1380072)

Utilizator alexb97Alexandru Buhai alexb97 Data 6 martie 2015 21:38:53
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("ctc.in");
ofstream os("ctc.out");

int n, m;
int idx;
vector <vector<int> > g, cc;
vector <int> index, L, c;
bitset<1000000> inStack;
stack<int> stk;

void Tarjan(int x);

int main()
{
    is >> n >> m;
    g = vector<vector < int > >(n + 1);
    index = vector < int >(n + 1, INF);
    L = vector < int >(n+1);
    int a, b;
    for(int i = 1; i <= m; ++i)
    {
        is >> a >> b;
        g[a].push_back(b);
    }
    for(int i = 1; i <= n; ++i)
    {
        if(index[i] == INF)
            Tarjan(i);
    }
    os << cc.size() << '\n';
    for(const auto& c: cc)
    {
        for(const auto& x : c)
            os << x << ' ';
        os << '\n';
    }
    is.close();
    os.close();
    return 0;
}

void Tarjan(int x)
{
    index[x] = L[x] = idx++;
    stk.push(x);
    inStack[x] = true;
    for(const auto& y: g[x])
    {
        if(index[y] == INF)
        {
            Tarjan(y);
            L[x] = min(L[x], L[y]);
        }
        else
            if(inStack[y])
            {
                L[x] = min(L[x], index[y]);
            }
    }
    if(index[x] == L[x])
    {
        c.clear();
        int x2;
        while(true)
        {
            x2 = stk.top();
            stk.pop();
            c.push_back(x2);
            inStack[x2] = false;
            if(x2 == x)
                    break;
        }
        cc.push_back(c);
    }
}