Cod sursa(job #1334853)

Utilizator RengelBotocan Bogdan Rengel Data 4 februarie 2015 18:53:18
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <vector>
#include <queue>

#define MAX_LENGTH 50005

using namespace std;

vector<int> neighborsList[MAX_LENGTH];
int extRank[MAX_LENGTH];

int main()
{
	freopen("sortaret.in", "r", stdin);
	freopen("sortaret.out", "w", stdout);

	int N, M;
	cin >> N >> M;

	int x, y;
	for (int i = 0; i < M; i++)
	{
		cin >> x >> y;

		neighborsList[x].push_back(y);
		extRank[y] += 1;
	}

	queue<int> queue;
	for (int i = 1; i <= N; i++)
	{
		if (extRank[i] == 0)
		{
			queue.push(i);
		}
	}

	while (!(queue.empty()))
	{
		int node = queue.front();
		queue.pop();

		cout << node << ' ';
		for (int i = 0; i < neighborsList[node].size(); i++)
		{
			extRank[neighborsList[node][i]] -= 1;
			if (extRank[neighborsList[node][i]] == 0)
			{
				queue.push(neighborsList[node][i]);
			}
		}
	}

	return 0;
}