Cod sursa(job #1909594)

Utilizator LaurIleIle Laurentiu Daniel LaurIle Data 7 martie 2017 13:13:57
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define nmax 50005
using namespace std;

int n, m;
int grad[nmax];
vector <int> G[nmax];
vector <int> sol;
queue <int> q;

void read()
{
    ifstream f("sortaret.in");
    f >> n >> m;
    for(int i=0, x, y; i<m; ++i)
    {
        f >> x >> y;
        G[x].push_back(y);
        ++grad[y];
    }
    f.close();
}

void solve()
{
    for(int i=1; i<=n; ++i)
    {
        if(!grad[i]) q.push(i);
    }

    while(q.size())
    {
        int x = q.front(); q.pop(); sol.push_back(x);
        for(int i=0; i<G[x].size(); ++i)
        {
            --grad[G[x][i]];
            if(!grad[G[x][i]])
                q.push(G[x][i]);
        }
    }
}

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

int main()
{
    read();
    solve();
    out();
    return 0;
}