Cod sursa(job #2172981)

Utilizator edi9876Negescu Eduard Mihai edi9876 Data 15 martie 2018 19:29:40
Problema Sortare topologica Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#include <vector>

using namespace std;

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

#define debug(a)\
{\
    out << #a << ' ' << a << '\n';\
}

const int N = 50000;

int n, m;
vector<int> v[N];
vector<int> b;
int pre[N] = {0}, des[N] = {0};
int nc = 0;

void bfs()
{
    //b.push_back(start);
    while(nc < b.size())
    {
        int x = b[nc++];
        out << x << " ";
        //pre[b[nc]]--;
        for(int i = 0; i < v[x].size(); i++)
        {
            int y = v[x][i];
            pre[y]--;
            if(pre[y] == 0)
            {
                b.push_back(y);
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        in >> x >> y;
        v[x].push_back(y);
        pre[y]++;
    }
    for(int i = 1; i <= n; i++)
    {
        if (pre[i] == 0)
        {
            b.push_back(i);
        }
    }
    bfs();
    out << ' ';
    return 0;
}