Cod sursa(job #2312148)

Utilizator VadimCCurca Vadim VadimC Data 4 ianuarie 2019 12:53:43
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

#define NMax 50005

int n, m;
vector<int> G[NMax];
int gr[NMax];

void init();
void rezolvare();

int main(){
	init();
	rezolvare();
}

void init(){
	int i, x, y;
	fin >> n >> m;
	for(i = 0; i < m; i++){
		fin >> x >> y;
		G[x].push_back(y);
		gr[y]++;
	}
}

void rezolvare(){
	queue<int> q;
	int i, x;
	for(i = 1; i <= n; i++)
		if(gr[i] == 0) q.push(i);
	while(!q.empty()){
		x = q.front(); q.pop();
		for(i = 0; i < G[x].size(); i++)
			if(--gr[G[x][i]] == 0) q.push(G[x][i]);
		fout << x << ' ';
	}
}