Pagini recente » Cod sursa (job #1814745) | Cod sursa (job #54731) | Cod sursa (job #1793431) | Cod sursa (job #587698) | Cod sursa (job #1229564)
#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) {
N = _N;
G.resize(N);
deg.resize(N);
}
void init(int _N) {
N = _N;
G.resize(N);
deg.resize(N);
}
void addUndirectedEdge(int x, int y) {
G[x].push_back(y);
++ deg[y];
}
vector <int> getTopologicalSort() {
return _getTopologicalSortBfs();
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;
}
vector <int> _getTopologicalSortBfs() {
vector<int> sortt;
queue <int> Q;
for(int i = 0 ; i < N ; ++ i)
if(!deg[i])
Q.push(i);
while(!Q.empty()) {
int node = Q.front();
Q.pop();
sortt.push_back(node);
for(It it = G[node].begin(), fin = G[node].end(); it != fin ; ++ it)
if(--deg[*it] == 0)
Q.push(*it);
}
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;
vector <int> deg;
} 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.begin(), fin = sortt.end(); it != fin ; ++ it)
fout << *it + 1 << ' ';
fin.close();
fout.close();
return 0;
}