Cod sursa(job #2904940)

Utilizator BarsanEmilianIoanBarsan Emilian-Ioan BarsanEmilianIoan Data 18 mai 2022 18:37:51
Problema Componente tare conexe Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
/* 
 * Componente Tare Conexe
 * Algoritmul lui Tarjan
 * 
 * Time Complexity:   O(m)
 * Memory Complexity: O(m)
 */ 
#include <fstream>
#include <vector>
#include <stack>
#include <set>
#include <bitset>
using namespace std;

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

using VB  = vector<bool>;
using SI  = set<int>;
using VI  = vector<int>;
using VVI = vector<VI>;
using VS = vector<SI>;

VVI G; 
VS ctc;   // 
VI index; // indexurile nodurilor in parcurgerea Dfs
VI L;     // indexurile minime
VB v;
SI c; 
bitset<100001> inStack;   
stack<int> stk; // retine nodurile in ordinea descoperirii acestora, la parcurgerea Df
int n, m;
int idx;  // indicii in ordinea descoperirii nodurilor

void CitesteGraf();
void CTC_Tarjan();
void Tarjan(int x);  // pe G

void ScrieCTC();

int main()
{
	CitesteGraf();
	CTC_Tarjan();
	ScrieCTC();
	
	return 0;
}

void CTC_Tarjan()
{
	for (int x = 1; x <= n; ++x)
		if (index[x] == 0)
			Tarjan(x);
}

void Tarjan(int x)
{
	index[x] = L[x] = ++idx;
	stk.push(x);
	inStack[x] = true;
	for (int y : G[x])
		if (!index[y]) // daca y e fiul lui x
		{
			Tarjan(y);
			L[x] = min(L[x], L[y]);
		}
		else
			if (inStack[y]) // daca x->y muchie de intoarcere (back-edge)
				L[x] = min(L[x], index[y]); 
	
	if (index[x] == L[x])
	{
		c.clear();
		while (true)
		{		
			int y = stk.top();
			stk.pop();
			inStack[y] = false;
			c.insert(y);
			
			if (y == x)
				break;
		}
		ctc.push_back(c);
	}
}

void ScrieCTC()
{
	fout << ctc.size() << '\n';
	
	for (auto c : ctc)
	{
		for (int x : c)
			fout << x << ' ';
		fout << '\n';
	}
}

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