Kyopro Library
 
読み取り中…
検索中…
一致する文字列を見つけられません
topological_sort.hpp
[詳解]
1#include"../../kyopro_library/template.hpp"
2
3/// @brief グラフ g をトポロジカルソートする
4/// @note グラフにサイクルがある場合は空の配列を返す
5/// @note O(V+E)
6vector<int> TopologicalSort(const vector<vector<int>>& g) {
7 int n=g.size();
8 vector<int> indeg(n);
9 for(int i=0; i<n; i++) for(int nxt:g[i]) indeg[nxt]++;
10 queue<int> que;
11 for(int i=0; i<n; i++) if(indeg[i]==0) que.push(i);
12 vector<int> ret;
13
14 while(!que.empty()) {
15 int now=que.front();
16 que.pop();
17 for(int nxt: g[now]) {
18 indeg[nxt]--;
19 if(indeg[nxt]==0) que.push(nxt);
20 }
21 ret.push_back(now);
22 }
23
24 if(ret.size()!=n) return {};
25 return ret;
26}
vector< int > TopologicalSort(const vector< vector< int > > &g)
グラフ g をトポロジカルソートする