Cod sursa(job #1728088)

Utilizator BlackNestaAndrei Manaila BlackNesta Data 12 iulie 2016 11:41:36
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
#define Nmax 50001
using namespace std;

queue <int> q;
vector <int> L[Nmax];
int n, m;
int d[Nmax], sol[Nmax], top;

void Citire()
{
    ifstream f("sortaret.in");
    f >> n >> m;
    int x, y;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> y;
        L[x].push_back(y);
        d[y]++;
    }
    f.close();
}

void BFS()
{
    int i, k, j;
    for(i = 1; i <= n; i++)
        if(d[i] == 0)
            {
                q.push(i);
                sol[++top] = i;
            }
    while(!q.empty())
    {
        k = q.front();
        q.pop();
        for(i = 0; i < L[k].size(); i++)
        {
            j = L[k][i];
            d[j]--;
            if(d[j] == 0)
                {
                    q.push(j);
                    sol[++top] = j;
                }
        }
    }
}

void Afisare()
{
    ofstream g("sortaret.out");
    for(int i = 1; i <= n; i++)
        g << sol[i] << " ";
    g << "\n";
    g.close();
}

int main()
{
    Citire();
    BFS();
    Afisare();
    return 0;
}