Cod sursa(job #2517845)

Utilizator PaulTPaul Tirlisan PaulT Data 4 ianuarie 2020 12:54:55
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

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

int n, m, nv;
VVI G, ctc;
VI niv, L, c;
stack<int> stk;
VB inStack;

void Read();
void Tarjan(int x);
void Write();

int main()
{
	Read();
	for (int x = 1; x <= n; x++)
		if (!niv[x])
			Tarjan(x);
	Write();
}

void Tarjan(int x)
{
	niv[x] = L[x] = ++nv;
	stk.emplace(x);
	inStack[x] = true;
	
	for (const int& y : G[x])
		if (!niv[y])
		{
			Tarjan(y);
			L[x] = min(L[x], L[y]);
		}
		else
			if (inStack[y])
				L[x] = min(L[x], niv[y]);
	
	if (L[x] == niv[x])
	{
		c.clear();
		while (!stk.empty())
		{
			int tp = stk.top();
			stk.pop();
			inStack[tp] = false;
			c.emplace_back(tp);
			if (tp == x)
				break;
		}
		ctc.emplace_back(c);
	}
}

void Write()
{
	ofstream fout("ctc.out");
	fout << ctc.size() << '\n';
	for (const VI& c : ctc)
	{
		for (const int& x : c)
			fout << x << ' ';
		fout << '\n';
	}
}

void Read()
{
	ifstream fin("ctc.in");
	fin >> n >> m;
	G = VVI(n + 1);
	niv = L = VI(n + 1);
	inStack = VB(n + 1);
	
	int x, y;
	while (m--)
	{
		fin >> x >> y;
		G[x].emplace_back(y);
	}
}