Cod sursa(job #2088635)

Utilizator marcdariaDaria Marc marcdaria Data 15 decembrie 2017 16:56:04
Problema Componente tare conexe Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
// Det Comp Tare Conexe 
// Alg. lui Tarjan
// O(m) 
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

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

enum {
	White, Gray, Black
};

using VI  = vector<int>;
using VVI = vector<VI>;
using VB  = vector<bool>;

int n, m;
VVI G;      // graful 
VI  niv;    // niv[x] = timpul de descoperire a nodului x (index)
VI L;
VI color;
VB inStack; 
int idx;    // timpul curent
VVI cc;     // retine comp tare conexe
VI c;       // comp tare conexa curenta           
stack<int> stk;

void ReadGraph();
void Tarjan(int x);
void StronglyConnectedComp();
void Write();

int main()
{
	ReadGraph();
	StronglyConnectedComp();
	Write();
	fin.close();
	fout.close();
}							

void StronglyConnectedComp()
{
	for (int x = 1; x <= n; ++x) // O(m)
		if (niv[x] == 0)
			Tarjan(x);
}

void Tarjan(int x)
{
	niv[x] = L[x] = ++idx;
	stk.push(x); inStack[x] = true;
	color[x] = Gray;
	for (const int& y : G[x])
		if (color[y] == White)  // tree edge
		{
			Tarjan(y);
			L[x] = min(L[x], L[y]);
		}
		else
			if (color[y] == Gray) // daca e in stiva, atunci e stramos => back edge
				L[x] = min(L[x], niv[y]);
	
	if (L[x] == niv[x]) // x e reprezentantul unei C.T.C
	{
		c.clear();
		while (!stk.empty())
		{
			int z = stk.top();
			stk.pop();
			inStack[z] = false;
			c.push_back(z);
			if (z == x)
				break;
		}
		cc.push_back(c);
	}
	color[x] = Black;
}

void ReadGraph()
{
	fin >> n >> m;
	G = VVI(n + 1);
	L = niv = color = VI(n + 1);
	
	inStack = VB(n + 1);
	int x, y;
	while (m--)
	{
		fin >> x >> y;
		G[x].push_back(y);
	}
}

void Write()
{
	fout << cc.size() << '\n';
	for (auto& c : cc)
	{
		for (auto& x : c)
			fout << x << ' ';
		fout << '\n';
	}
}