Cod sursa(job #2538461)

Utilizator iustin948Homoranu Iustin iustin948 Data 4 februarie 2020 19:18:32
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 50005
#include <queue>
using namespace std;
ifstream fin("sortaret.in");
ofstream fout("sortaret.out");
int n, m, G[NMAX];
vector <int> graph[NMAX];
bool visited[NMAX];
queue <int> nodes;
void Read()
{
    int x, y;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        graph[x].push_back(y);
        G[y]++;
    }
}

void Solve()
{
   int i, j, x;
   for(i = 1; i <= n; i++)
   if(G[i] == 0) nodes.push(i);
   for(i = 1; i <= n; i++)
   {
       x = nodes.front();
       nodes.pop();
       fout << x << " ";
       for(auto w : graph[x])
       {
           G[w]--;
           if(G[w] == 0) nodes.push(w);
       }
   }
}

int main()
{
    Read();
    Solve();
    return 0;
}