拓扑排序适用于无环图,且图是有向的,而且要有入度为0的结点
分析:使用map存储结点和结点的入度信息,使用队列存储入度为0的信息,依次弹出队列中入度为0的结点,并把与之相连的结点入度减1,如果为零就加入到队列中,最后用一个链表记录输出顺序
//拓扑排序
list<Node*> Sort(Graph graph)
{
unordered_map<Node*,int>m;
queue<Node*>q;
unordered_map<int,Node*>::iterator ite = graph.nodes.begin();
while (ite != graph.nodes.end())
{
m[ite->second] = ite->second->in;
if (ite->second->in == 0)
q.push(ite->second);
ite++;
}
list<Node*>res;
while (!q.empty())
{
Node* h = q.front();
res.push_back(h);
for (Node* temp : h->next)
{
if (--m[temp] == 0)
q.push(temp);
}
}
return res;
}