Cod sursa(job #2665971)

Utilizator TheSharkCristian-Andrei Ionescu TheShark Data 31 octombrie 2020 16:16:50
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include<fstream>
#include<vector>
#include<deque>
#define NMAX 100001

using namespace std;

ifstream in("sortaret.in");
ofstream out("sortaret.out");

vector<unsigned int> adjList[NMAX];
bool isVisited[NMAX];

deque<unsigned int> sortedGraph;

void dfs(unsigned int startNode) {

	isVisited[startNode] = true;
	for (const auto& node : adjList[startNode]) {
		if (!isVisited[node]) {
			dfs(node);
		}
	}

	sortedGraph.push_front(startNode);
}

void printResult() {
	for (deque<unsigned int>::iterator node = sortedGraph.begin(); node != sortedGraph.end(); node++) {
		out << *node << ' ';
	}
	out << "\n";
}

int main() {

	unsigned int N, M;

	in >> N >> M;
	for (unsigned int i = 0; i < M; ++i) {
		unsigned int startNode, endNode;
		in >> startNode >> endNode;
		adjList[startNode].push_back(endNode);
	}

	for (unsigned int node = 1; node <= N; ++node) {
		if (!isVisited[node]) {
			dfs(node);
		}
	}

	printResult();

	return 0;
}