Cod sursa(job #2419674)

Utilizator andrei828Ungureanu Andrei-Liviu andrei828 Data 9 mai 2019 10:49:33
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <fstream>
#include <vector>

std::ifstream fin("sortaret.in", std::ifstream::in);
std::ofstream fout("sortaret.out", std::ofstream::out);

int n, m;
std::vector<int> degrees;
std::vector<std::vector<int>> graph;

void read();
std::vector<int> sortaret(std::vector<std::vector<int>>& graph, std::vector<int> degrees);

int main() {
	read();

	std::vector<int> x = sortaret(graph, degrees);
	for (auto i: x)
		fout << i << ' ';
}

std::vector<int> sortaret(std::vector<std::vector<int>>& graph, std::vector<int> degrees) {
	std::vector<int> result;
	bool ok;
	while (1) {
		ok = false;
		for (int i = 1; i < degrees.size(); i++) {
			if (degrees[i] == 0) {
				ok = true;

				result.push_back(i);
				degrees[i] = -1;

				for (int j = 0; j < graph[i].size(); j++) {
					degrees[graph[i][j]]--;
				}
			}
		}

		if (!ok)
			return result;
	}
}

void read() {

	fin >> n >> m;
	degrees = std::vector<int>(n + 1, 0);
	graph = std::vector<std::vector<int>>(n + 1);
	int tmp1, tmp2;
	for (int i = 0; i < m; i++)  {
		fin >> tmp1 >> tmp2;
		graph[tmp1].push_back(tmp2);
		degrees[tmp2]++;
	}

}