在计算机科学领域,有向图的拓扑排序是其顶点的线性排序,使得对于从顶点{\displaystyle u}到顶点{\displaystyle v}的每个有向边{\displaystyle uv},{\displaystyle u}在排序中都在{\displaystyle v}之前。 例如,图形的顶点可以表示要执行的任务,并且边可以表示一个任务必须在另一个任务之前执行的约束; 在这个应用中,拓扑排序只是一个有效的任务顺序。 如果且仅当图形没有定向循环,即如果它是有向无环图(DAG),则拓扑排序是可能的。 任何 DAG 具有至少一个拓扑排序,并且已知这些算法用于在线性时间内构建任何 DAG 的拓扑排序。
在图论中,由一个有向无环图的顶点组成的序列,当且仅当满足下列条件时,称为该图的一个拓扑排序(英语:Topological sorting)。
- 每个顶点出现且只出现一次;
- 若A在序列中排在B的前面,则在图中不存在从B到A的路径。
TOPO_H
#pragma once
#ifndef TOPO_H
#define TOPO_H
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Graph
{
int vex;
int edg;
int ** arc;//链接矩阵
};
void createGraph(Graph& g);
void printGraph(Graph g);
void Findindegree(Graph g,int indegree[]);//求每个顶点的入度
void TopoSort(Graph g);//进行拓扑排序
#endif
Topo.cpp
#include"Topo.h"
#include<stack>
#include<vector>
#define max 1000000
void createGraph(Graph& g)
{
cout << "请输入顶点数" << endl;
cin >> g.vex;
cout << "请输入边数" << endl;
cin >> g.edg;
//g.information = new string[g.vex];
g.arc = new int *[g.vex];
int i = 0;
//开辟空间的同时进行名称的初始化
for (i = 0; i < g.vex; i++)
{
g.arc[i] = new int[g.vex];
//g.information[i] = "v" + to_string(i + 1);
for (int k = 0;k < g.vex;k++)
{
g.arc[i][k] = max;
}
}
cout << "请输入每条边之间的顶点编号:" << endl;
int start;
int end;
for (i = 0;i < g.edg;i++)
{
cin >> start;
cin >> end;
g.arc[start][end] = 1;
//g.arc[end][start] = weight;
}
}
void printGraph(Graph g)
{
int i;
for (i = 0;i < g.vex;i++)
{
for (int j = 0;j < g.vex;j++)
{
if (g.arc[i][j] == max)
cout << "*" << " ";
else
{
cout << g.arc[i][j] << " ";
}
}
cout << endl;
}
}
void Findindegree(Graph g, int indegree[])
{
for (int j = 0;j < g.vex;j++)
{
for (int i = 0;i < g.vex;i++)
{
if (g.arc[i][j] != max)
indegree[j]++;
}
}
}
void TopoSort(Graph g)
{
int *indegree;
indegree = new int[g.vex];
for (int i = 0;i < g.vex;i++)
{
indegree[i] = 0;
}
Findindegree(g, indegree);
stack<int> Q;
for (int i = 0;i < g.vex;i++)
{
cout << indegree[i] << " ";
}
for (int i = 0;i < g.vex;i++)
{
if (!indegree[i])
{
Q.push(i);
indegree[i] = -1;
}
}
int count = 0;
while (!Q.empty())
{
int temp = Q.top();
cout << temp << " ";
Q.pop();
count++;
for (int i = 0;i < g.vex;i++)
{
if (g.arc[temp][i] != max)
--indegree[i];
if (indegree[i] == 0)
{
Q.push(i);
indegree[i] = -1;
}
}
}
if (count < g.vex) cout<<"ERROR";
else cout<<"OK";
}
main.cpp
#include"Topo.h"
#include<iostream>
using namespace std;
int main()
{
Graph g;
createGraph(g);
printGraph(g);
TopoSort(g);
}
附上一段运行的截图