Cod sursa(job #2298475)

Utilizator Catalin_BorzaBorza Catalin-Mihai Catalin_Borza Data 8 decembrie 2018 10:48:37
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>
using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

int n, m;
vector<int> G[100001], GT[100001], rez;
bitset<100001> viz, viz2;
stack<int> s;

void read()
{
	int x, y;
	f >> n >> m;
	for (int i = 0; i < m; i++)
	{
		f >> x >> y;
		G[x].push_back(y);
		GT[y].push_back(x);
	}
}

void kosaraju2(int i)
{
	viz2[i] = 1;
	if (s.empty())
		return;
	for (auto it : GT[i])
		if (!viz2[it])
			kosaraju2(it);
	rez.push_back(i);
}

void kosaraju1(int i)
{
	s.push(i);
	viz[i] = 1;
	for (auto it : G[i])
		if (!viz[it])
			kosaraju1(it);
}

int main()
{
	read();
	kosaraju1(1);
	while (!s.empty())
	{
		int x;
		while (!s.empty() && viz2[s.top()]) s.pop();
		if (!s.empty())
		{
			x = s.top();
			s.pop();
			kosaraju2(x);
			for (auto it : rez) g << it << " ";
			rez.clear();
			g << "\n";
		}
	}
	
	for (int i = 2; i <= n; i ++)
		if (!viz[i])
		{
			kosaraju1(i);
			while (!s.empty())
			{
				int x;
				while (!s.empty() && viz2[s.top()]) s.pop();
				if (!s.empty())
				{
					x = s.top();
					s.pop();
					kosaraju2(x);
					for (auto it : rez) g << it << " ";
					rez.clear();
					g << "\n";
				}
			}
		}
	return 0;
}