Cod sursa(job #2198051)

Utilizator al.mocanuAlexandru Mocanu al.mocanu Data 23 aprilie 2018 14:22:28
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <stack>
#define MAX 100005
using namespace std;

int n, m, x, y;
int ind, index[MAX], lowlink[MAX];
bool onStack[MAX], viz[MAX];
vector<int> l[MAX], c;
stack<int> s;
vector<vector<int> > ctc;

void tarjan(int x) {
    viz[x] = 1;
    index[x] = lowlink[x] = ind++;
    s.push(x);
    onStack[x] = 1;

    for(int i = 0; i < l[x].size(); ++i)
        if(!viz[l[x][i]]) {
            tarjan(l[x][i]);
            lowlink[x] = min(lowlink[x], lowlink[l[x][i]]);
        }
        else if(onStack[l[x][i]])
            lowlink[x] = min(lowlink[x], index[l[x][i]]);

    if(lowlink[x] == index[x]) {
        int node;
        c.clear();
        do {
            node = s.top();
            s.pop();
            onStack[node] = 0;
            c.push_back(node);
        } while(node != x);

        ctc.push_back(c);
    }
}

int main() {
    ifstream f("ctc.in");
    ofstream g("ctc.out");

    f >> n >> m;
    for(int i = 0; i < m; ++i) {
        f >> x >> y;
        l[x].push_back(y);
    }

    for(int i = 1; i <= n; ++i)
        if(!viz[i])
            tarjan(i);

    g << ctc.size() << "\n";
    for(int i = 0; i < ctc.size(); ++i) {
        for(int j = 0; j < ctc[i].size(); ++j)
            g << ctc[i][j] << " ";
        g << "\n";
    }

    return 0;
}