Cod sursa(job #1156422)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 27 martie 2014 17:30:13
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.66 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "sortaret.in";
const char outfile[] = "sortaret.out";

ofstream fout(outfile);

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

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

const int lim = 1 << 10;
char buffer[lim];
int pos;
int deg[MAXN], N, M;
Graph G;
bitset <MAXN> Used;

inline void get(int &nr) {
    nr = 0;
    while(!('0' <= buffer[pos] && buffer[pos] <= '9')) {
        if(++ pos == lim) {
            fread(buffer, 1, lim, stdin);
            pos = 0;
        }
    }
    while(('0' <= buffer[pos] && buffer[pos] <= '9')) {
        nr = nr * 10 + buffer[pos] - '0';
        if(++ pos == lim) {
            fread(buffer, 1, lim, stdin);
            pos = 0;
        }
    }
}

inline vector <int> topologicalSortQ() {
    vector <int> tsort;
    queue <int> Q;
    for(int i = 1 ; i <= N ; ++ i)
        if(deg[i] == 0)
            Q.push(i);
    while(!Q.empty()) {
        int Node = Q.front();
        tsort.push_back(Node);
        Q.pop();
        for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it) {
            if(-- deg[*it] == 0)
                Q.push(*it);
        }
    }
    return tsort;
}

inline void DFs(int Node, vector <int> &tsort) {
    if(Used[Node])
        return;
    Used[Node] = 1;
    for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it)
        DFs(*it, tsort);
    tsort.push_back(Node);
}

inline vector <int> topologicalSortDfs() {
    vector <int> tsort;
    for(int i = 1 ; i <= N ; ++ i)
        if(!Used[i])
            DFs(i, tsort);
    return tsort;
}

int main() {
    freopen(infile, "r", stdin);
    get(N);
    get(M);
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        get(x);
        get(y);
        G[x].push_back(y);
        ++ deg[y];
    }
    vector <int> Ans = topologicalSortDfs();
    for(vector<int> :: reverse_iterator it = Ans.rbegin(), fin = Ans.rend(); it != fin ; ++ it)
        fout << *it << ' ';
    fout.close();
    return 0;
}