思想:
维护一个入度为0的节点队列,每次出队一个并打印,然后删除所有从该节点出发的路径,并更新各个节点的入度,再次入队一个入度为0的节点,直至队列为空。
/*topological sort of dag*/
#include<bits/stdc++.h>
using namespace std;
class graph
{
public:
graph(int V);
~graph();
void addedg(int v, int w);
void topological_sort();
private:
int V;//顶点数
list<int>* adj;//邻接表
queue<int>q;//维护入度为0的队列
int* indgree;//记录节点的入度
};
graph::graph(int V)
{
this->V = V;
adj = new list<int>[V];
indgree = new int[V];
for (int i = 0; i < V; i++)
{
indgree[i] = 0;
}
}
graph::~graph()
{
delete[] adj;
delete[] indgree;
}
void graph::addedg(int v,int w)//v指向w
{
adj[v].push_back(w);
indgree[w]++;
}
void graph::topological_sort()
{
for (int i = 0; i < V; ++i)
{
if (indgree[i] == 0)q.push(i);
}
while (!q.empty())
{
int t = q.front();
q.pop();
cout << t << " ";
auto f = adj[t].begin();
for (; f != adj[t].end(); ++f)
{
indgree[*f]--;
if (indgree[*f] == 0)q.push(*f);
}
}
}
int main()
{
graph g(6);
g.addedg(5, 2);
g.addedg(5, 0);
g.addedg(4, 0);
g.addedg(4, 1);
g.addedg(2, 3);
g.addedg(3, 1);
g.topological_sort();
return 0;
}