Cod sursa(job #2655237)

Utilizator PaulTPaul Tirlisan PaulT Data 3 octombrie 2020 17:49:00
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

int n, m;
VVI G;
stack<int> stk;
VB seen;

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

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

void Dfs(int x)
{
	seen[x] = true;
	for (const int& y : G[x])
		if (!seen[y])
			Dfs(y);
	stk.push(x);
}

void Write()
{
	ofstream fout("sortaret.out");
	while (!stk.empty())
	{
		fout << stk.top() << ' ';
		stk.pop();
	}
}

void Read()
{
	ifstream fin("sortaret.in");
	fin >> n >> m;
	G = VVI(n + 1);
	seen = VB(n + 1);
	
	int x, y;
	for (int i = 0; i < m; i++)
	{
		fin >> x >> y;
		G[x].emplace_back(y);
	}
}