Cod sursa(job #2425085)

Utilizator Mihaibv13Mihai Stoian Mihaibv13 Data 24 mai 2019 11:47:03
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <vector>
#include <stack>
#include <set>
#include <fstream>
#include <climits>
using namespace std;

int visited[50001];
int main()
{
	ifstream fin;
	ofstream fout;
	fin.open("sortaret.in");
	fout.open("sortaret.out");
	int nodeCount, edgeCount;
	vector<int> edges[50001];
	fin >> nodeCount >> edgeCount;
	for(int i=1;i<=edgeCount;i++)
	{
		int node1, node2;
		fin >> node1 >> node2;
		edges[node1].push_back(node2);
	}
	stack<int> st;
	stack<int> sorted;
	for (int i = 1; i <= nodeCount; i++)
	{
		if(visited[i])continue;
		st.push(i);
		while (!st.empty())
		{
			int thisNode = st.top();
			int ok = 0;
			for (auto nextNode : edges[thisNode])
			{
				if (!visited[nextNode])
				{
					visited[nextNode] = 1;
					st.push(nextNode);
					ok = 1;
				}
			}
			if (ok == 0)
			{
				sorted.push(thisNode);
				st.pop();
			}
		}
	}
	while(!sorted.empty())
	{
		fout << sorted.top()<<" ";
		sorted.pop();
	}
	return 0;
}