Cod sursa(job #1254258)

Utilizator vladrochianVlad Rochian vladrochian Data 2 noiembrie 2014 13:57:49
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

const int kMaxN = 100005;

ifstream fin("ctc.in");
ofstream fout("ctc.out");

int N, M, ctc_n;
vector<int> G[kMaxN], T[kMaxN], ctc[kMaxN];
stack<int> st;
bool use[kMaxN];

void NormalDFS(int node) {
	use[node] = true;
	for (int i : G[node])
		if (!use[i])
			NormalDFS(i);
	st.push(node);
}
void TransposeDFS(int node) {
	use[node] = false;
	ctc[ctc_n].push_back(node);
	for (int i : T[node])
		if (use[i])
			TransposeDFS(i);
}

void Read() {
	fin >> N >> M;
	while (M--) {
		int x, y;
		fin >> x >> y;
		G[x].push_back(y);
		T[y].push_back(x);
	}
}
void Kosaraju() {
	for (int i = 1; i <= N; ++i)
		if (!use[i])
			NormalDFS(i);
	while (!st.empty()) {
		if (use[st.top()]) {
			++ctc_n;
			TransposeDFS(st.top());
		}
		st.pop();
	}
}
void Print() {
	fout << ctc_n << "\n";
	for (int i = 1; i <= ctc_n; ++i) {
		for (int node : ctc[i])
			fout << node << " ";
		fout << "\n";
	}
}

int main() {
	Read();
	Kosaraju();
	Print();
	return 0;
}