Cod sursa(job #1609572)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 22 februarie 2016 21:14:51
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>

using namespace std;

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

const int dimn = 100005;

int n, m, currLevel = 0;

int level[dimn], low[dimn];

vector<int> graph[dimn];
stack<int> st;

int ctcCount = 0;
vector< vector<int> > ctc;

void dfs(int node) {

	level[node] = ++currLevel;
	low[node] = currLevel;

	st.push(node);

	for (vector<int>::iterator adj = graph[node].begin(); adj != graph[node].end(); ++adj) {

		if (level[*adj] == 0)
			dfs(*adj);

		if (level[*adj] > 0)
			low[node] = min(low[node], low[*adj]);

	}

	if (level[node] == low[node]) {

		++ctcCount;
		ctc.push_back(vector<int>(0));

		int x;
		do {
			
			x = st.top();
			st.pop();
			level[x] *= -1;
			ctc[ctcCount - 1].push_back(x);
		

		} while (x != node);

	}

}

int main() {

	fin >> n >> m;

	for (int i = 1; i <= m; ++i) {

		int x, y;
		fin >> x >> y;

		graph[x].push_back(y);

	}

	for (int i = 1; i <= n; ++i) {

		if (level[i] != 0)
			continue;

		dfs(i);

	}

	fout << ctcCount << '\n';

	for (int i = 0; i < ctcCount; ++i) {
		for (unsigned int j = 0; j < ctc[i].size(); ++j)
			fout << ctc[i][j] << ' ';
		fout << '\n';
	}

	return 0;

}

//Trust me, I'm the Doctor!