在图论中,拓扑排序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列。
拓扑排序结果的要求:
1,每个顶点出现且只出现一次。
2,若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面。
注意:无向图没有没有拓扑排序,因为无法满足条件2
过程:
1,输出没有前驱节点的一个节点
2,将输出的节点删除
3,重复 1,2 直到全部输出
#include <bits/stdc++.h>
using namespace std;
bool check(map<string,set<string>> m,map<string, set<string>>::iterator t)
{
for(auto elem : m)
{
if(elem.second.find(t->first) != elem.second.end())
{
return false;
}
}
return true;
}
void T_sort(map<string,set<string>> m)
{
while(!m.empty())
{
auto t = m.begin();
while(!check(m,t)) ++t;
cout << t->first << endl;
m.erase(t);
}
}
int main()
{
map<string,set<string>> m;
set<string> nothing;
for(int i = 1;i <= 5;++i) m.insert({to_string(i),nothing});
for(int i = 0;i < 7;++i)
{
string x,y;
cin >> x >> y;
m[x].insert(y);
}
T_sort(m);
return 0;
}
/*
1 4
1 2
2 4
2 3
3 5
4 3
4 5
*/
然后我们在用队列的方法求拓扑排序:
1,入度为0的入队
2,头节点出队输出,然后将所有头节点的邻接点入度-1
3,在2邻接点入度-1时,如果入度为0了,就入队
重复2,3直到队列为空
伪代码:
void TopSort()
{
for(each vertex V in the graph)
{
if(Indegree[V] == 0) //这里把所有入度为0的顶点入队
Enqueue(V, Q);
}
while(!IsEmpty(Q))
{
V = Dequeue(Q); //从队列中取出顶点,该顶点的入度一定为0
输出(V); // 输出V,或者记录V的输出序号
cnt++; //记录输出的顶点的个数,用于判断图中是否有回路
for(each adjacent vertex W of V) //把V的所有邻接点的入度都减1
{
if(--Indegree[W] == 0)
Enqueue(W, Q);
}
}
if(cnt != number of vertices in the graph) //判断输出顶点的个数(即入度为0的顶点个数)是否与图中的顶点数量相等,如果不相等,则说明图中有回路
Error("The graph contains a cycle");
}
下图代码:
A B 5
A D 2
A E 7
B D 3
D E 1
B C 1
E C 9
E F 4
E G 3
F G 1
#include <bits/stdc++.h>
using namespace std;
vector<string> T_sort(map<string,map<string,int>> m)
{
vector<string> res;
deque<string> d;
//先遍历一次活得入度
map<string,int> check;
for(auto elem : m) check[elem.first] = 0;
for(auto elem1 : m)
{
for(auto elem2 : elem1.second)
{
++check[elem2.first];
}
}
//开始拓扑
for(auto elem : check)
{
if(elem.second == 0) d.push_back(elem.first);
}
while(!d.empty())
{
string head = d.front();
res.push_back(head);
for(auto elem : m[head])
{
--check[elem.first];
if(check[elem.first] == 0) d.push_back(elem.first);
}
d.pop_front();
}
return res;
}
int main()
{
map<string,map<string,int>> m;
for(int i = 0;i < 10;++i)
{
string x,y;
int n;
cin >> x >> y >> n;
m[x].insert({y,n});
}
vector<string> v = T_sort(m);
return 0;
}
/*
A B 5
A D 2
A E 7
B D 3
D E 1
B C 1
E C 9
E F 4
E G 3
F G 1
*/