運用dfs,對乙個有向無回圖(dag)進行拓撲排序。
乙個圖的拓撲排序可看成所有頂點沿水平線排列而成的乙個序列,使得所有有向邊均從左指向右。
topological-sort(g)
call dfs(g) to compute finishing times f[v] for each vertex v
as each vertex is finished, insert it onto the front of a linked list // stack也可
return the linked list of verteces
經拓撲排序的頂點,按照完成時間的遞減排序。在dfs中越早完成,在拓撲排序越後面。
uva10305
#include
#include
#include
#include
#include
#include
using
namespace
std;
const
intmaxn =
105;
stack<
int> stk;
intd[maxn];
intf[maxn];
intcolor[maxn];
vector<
int> mp[maxn];
inttme = 0;
void
dfs(
intx)
} f[x] = tme ++;
stk.push(x);
color[x] = 1;
// }
intmain()
memset(d, -1,
sizeof
(d));
memset(f, -1,
sizeof
(f));
memset(color, -1,
sizeof
(color));
while
(!stk.empty())
inta,b;
for(int
i =0
; i < m; i ++)
for(int
i =1
; i <= n; i ++) }
bool
fr =
true;
while
(!stk.empty())
else
cout <<
" ";
cout << stk.top() ;
stk.pop(); }
cout << endl; }
return0;
}
拓撲排序 dfs
include include includeusing namespace std const int maxn 50 typedef struct nodenode typedef struct graphgraph vectorss 存放拓撲序列 bool vis maxn int find ...
拓撲排序DFS做法
1 給定乙個有向圖,在拓撲排序中可以 有很多個正確解 由若干小段的 list 組成。2 正確的單序列順序 具體到乙個list之間的元素 3 正確的全序列順序 list彼此之間的順序,可以有多個 e.g.以下圖為例,不論先從哪個點開始 dfs,例如 dfs belt 會得到乙個 belt jacket...
拓撲排序 kahn演算法及dfs的拓撲排序
有個人的家族很大,輩分關係很混亂,請你幫整理一下這種關係。給出每個人的孩子的資訊。輸出乙個序列,使得每個人的後輩都比那個人後列出 sample input 5 0 4 5 1 0 1 0 5 3 0 3 0樣例輸出 sample output 2 4 5 3 1 因為需輸出字典序最小的因而要使用優先...