Cod sursa(job #902658)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 1 martie 2013 15:53:16
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <cstdio>
#include <cstring>
#include <cassert>

#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <map>

using namespace std;

typedef long long LL;
typedef vector<int>::iterator it;

const int oo = 0x3f3f3f3f;
const int MAX_N = 50005;

vector<int> G[MAX_N];
int N, TSort[MAX_N];
bool Used[MAX_N];

void DFS(int X) {
    Used[X] = true;
    for (it Y = G[X].begin(); Y != G[X].end(); ++Y)
        if (!Used[*Y])
            DFS(*Y);
    TSort[++TSort[0]] = X;
}

void Solve() {
    for (int X = 1; X <= N; ++X)
        if (!Used[X])
            DFS(X);
    reverse(TSort + 1, TSort + TSort[0] + 1);
}

void Read() {
    assert(freopen("sortaret.in", "r", stdin));
    int M; assert(scanf("%d %d", &N, &M) == 2);
    for (; M > 0; --M) {
        int X, Y; assert(scanf("%d %d", &X, &Y) == 2);
        G[X].push_back(Y);
    }
}

void Print() {
    assert(freopen("sortaret.out", "w", stdout));
    for (int i = 1; i <= N; ++i)
        printf("%d ", TSort[i]);
    printf("\n");
}

int main() {
    Read();
    Solve();
    Print();
    return 0;
}