Cod sursa(job #1229546)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 17 septembrie 2014 17:46:10
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 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";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
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; }

class UndirectedGraph {
public:
    UndirectedGraph() {
    }
    UndirectedGraph(int _N) {
        this->N = _N;
        G.resize(N);
    }
    void init(int  _N) {
        this->N = _N;
        G.resize(N);
    }
    void addUndirectedEdge(int x, int y) {
        G[x].push_back(y);
    }
    vector <int> getTopologicalSort() {
        return _getTopologicalSortDfs();
    }
private:
    vector <int> _getTopologicalSortDfs() {
        vector <bool> used(N);
        vector <int> sortt;
        for(int i = 0 ; i < N ; ++ i)
            if(!used[i])
                dfs(i, used, sortt);
        return sortt;
    }
    void dfs(int node, vector <bool> &used, vector <int> &sortt) {
        used[node] = 1;
        for(It it = G[node].begin(), fin = G[node].end(); it != fin ; ++ it)
            if(!used[*it])
                dfs(*it, used, sortt);
        sortt.push_back(node);
    }
    int N;
    vector <vector <int> > G;
} G;

int N, M;

int main() {
    fin >> N >> M;
    G.init(N);
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        fin >> x >> y;
        -- x;
        -- y;
        G.addUndirectedEdge(x, y);
    }
    vector <int> sortt = G.getTopologicalSort();
    for(auto it = sortt.rbegin(), fin = sortt.rend(); it != fin ; ++ it)
        fout << *it + 1 << ' ';
    fin.close();
    fout.close();
    return 0;
}