Cod sursa(job #2168226)

Utilizator loo_k01Luca Silviu Catalin loo_k01 Data 14 martie 2018 10:06:09
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>
using namespace std;
const int Nmax = 50002;

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

int d[Nmax];
int gr[Nmax];
vector < int > L[Nmax];
int N, M;

struct Graf
{
    int nod;
    bool operator < (const Graf &e) const
    {
        return nod > e.nod;
    }
};
priority_queue < Graf > q;

void Read()
{
    int i, x ,y;
    fin >> N >> M;
    for (i = 1;  i <= M; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
        gr[y]++;
    }
    fin.close();
}

void BFS()
{
    int i, nod;
    for (i = 1; i <= N; i++)
        if (gr[i] == 0)
            q.push({i});

    while(!q.empty())
    {
        nod = q.top().nod;
        q.pop();
        fout << nod << " ";
        for (auto w : L[nod])
        {
            gr[w]--;
            if(gr[w] == 0)
                q.push({w});
        }
    }
    fout << "\n";
}

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