Cod sursa(job #2187456)

Utilizator MatteusTanase Matei Matteus Data 26 martie 2018 15:31:18
Problema Sortare topologica Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;

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

const int N = 50001;
vector<int> a[N];

int n, m, nrp[N], coada[N], st, dr, viz[N], stop[N], nr;

void read() {
    int i, x, y;
    fin >> n >> m;

    for (i = 1; i <= m; i++) {
        fin >> x >> y;

        a[x].push_back(y);
        nrp[y]++;
    }

    /*st = 1, dr = 0;

    for (i = 1; i <= n; i++)
        if (nrp[i] == 0)
            coada[++dr] = i;
*/}

void bfs_topologic() {
    int i, y;

    while (st <= dr) {
        int nod = coada[st++];
        fout << nod << ' ';

        for (i = 0; i < a[nod].size(); i++) {
            y = a[nod][i];
            nrp[y]--;

            if (nrp[y] == 0)
                coada[++dr] = y;
        }
    }
}

void dfs(int x)
{
    viz[x]=1;
    for(int i=0; i<a[x].size(); i++)
    {
        int y=a[x][i];
        if(!viz[y])
            dfs(y);
    }
    stop[++nr]=x;
}

int main()
{
    read();
    //bfs_topologic();
    for(int i=1; i<=n; i++)
        dfs(i);
    for(int i=n; i>=1; i--)
        fout<<stop[i]<<' ';
    return 0;
}