Cod sursa(job #2102980)

Utilizator Dobricean_IoanDobricean Ionut Dobricean_Ioan Data 9 ianuarie 2018 17:53:39
Problema Componente tare conexe Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
/* Det comp Tare Conexe ale unui graf Orientat
 * Alg. Lui Tarjan  O(m)
 */ 

#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

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

VVI G; // graful dat
VVI cc;      
VI c, niv, L; // niv retine indexul (timpul de descoperire a fiecarui nod)
VB inStack;
int n, m, idx;

stack<int> stk;  

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

int main() 
{
	ReadGraph();
	StronglyConnected();
	Write();
}

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

void Tarjan(int x) 
{	
	niv[x] = L[x] = idx++;
	stk.push(x);
	inStack[x] = true;
	
	for (const int& y : G[x])
		if (!niv[y])          // tree edge
		{
			Tarjan(y);
			L[x] = min(L[x], L[y]);
		}
		else 
			if (inStack[y])
				L[x] = min(L[x], niv[y]);
	
	int y;
	if (niv[x] == L[x])
	{
		c.clear();
		while (!stk.empty())
		{
			y = stk.top();
			stk.pop();
			inStack[y] = false;
			c.push_back(y);
			if (y == x)
				break;
		}
		
		cc.push_back(c);
	}
}


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

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