Cod sursa(job #2120944)

Utilizator k.bruenDan Cojocaru k.bruen Data 3 februarie 2018 10:03:11
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <vector>
#include <stack>

std::ifstream in("ctc.in");
std::ofstream out("ctc.out");

const int MAX = 100000;

std::vector<int> Graf[MAX];
std::stack<int> Stack;
int index[MAX];
int lowlink[MAX];
bool instack[MAX];

int _index = 1;

void strongconnect(int v) {
	index[v] = lowlink[v] = _index++;
	Stack.push(v);
	instack[v] = true;

	for (int w : Graf[v]) {
		if (index[w] == 0) {
			strongconnect(w);
			lowlink[v] = (lowlink[w] > lowlink[v]) ? lowlink[v] : lowlink[w];
		}
		else if (instack[w]) {
			lowlink[v] = (index[w] > lowlink[v]) ? lowlink[v] : index[w];
		}
	}

	if (lowlink[v] == index[v]) {
		int w;
		do {
			w = Stack.top(); Stack.pop();
			instack[w] = false;

			out << w << ' ';
		} while (w != v);
		out << '\n';
	}
}

int main() {
	std::ios::sync_with_stdio(false);

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

	for (int i = 0; i < n; ++i) {
		if (index[i] == 0) {
			strongconnect(i);
		}
	}

	return 0;
}