Cod sursa(job #1128616)

Utilizator thebest001Neagu Rares Florian thebest001 Data 27 februarie 2014 17:52:43
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 kb
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
#define MAX 50001 

vector<int> a[MAX];
int pred[MAX];
queue<int> q;
int n, m;

void bf(){
	while (!q.empty()) {
		int t = q.front();
		printf("%d ",t);
		q.pop();
		
		for (vector<int>::iterator i = a[t].begin(); i != a[t].end(); i++) {
			--pred[*i];
			if (pred[*i] == 0) 
				q.push(*i);
		}

	}
}

int main() {
	freopen("sortaret.in", "r", stdin);
	freopen("sortaret.out", "w", stdout);
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= m; i++) {
		int x, y;
		scanf("%d %d", &x, &y);
		a[x].push_back(y);
		pred[y]++;
	}
	for (int i = 1; i <= n; i++){
		if (pred[i] == 0)
			q.push(i);
	}
	
	bf();

	return 0;
}