//拓扑排序
//主要思路:只能输出入度为0的顶点,输出后去除依附与他的边,重复该操作纸质所有顶点被输出
//主要操作:寻找入度为0的顶点入栈,随后出栈并输出,之后将以其为尾的另一头的顶点入度-1
//(相当于除去了一条边),此时若有顶点的入度被减后为0也可入栈。重复上述操作直至栈空
//(每个顶点入度为0都会入栈,之后输出都会出栈,因此每个顶点都入栈仅一次,栈空即所有顶点都被输出过了)
#include<iostream>
#include<stdlib.h>
#include<stack>
using namespace std;
#define MAX_VERTEX 10
struct Node
{
int data;//除首节点外的代表节点的数据均为该数据存储在数组中的下标
struct Node* next;
};
struct Graph
{
Node* head; //顶点(首节点)数组
int vn; //顶点数
int en; //边数
};
//给顶点数据返回顶点下标
int Located(Graph g, int x)
{
for (int i = 0; i < g.vn; i++)
if (g.head[i].data == x)
return i;
return 100;
}
//邻接表存储,边中代表顶点的数据均为其存储在顶点数组中的下标
void CreateGraph(Graph& g)
{
g.head = (Node*)malloc(MAX_VERTEX * sizeof(Node));
cout << "Input vertex numbers and edge numbers: ";
cin >> g.vn>>g.en;
cout << "Input vertexs: "<<endl;
for (int i = 0; i < g.vn; i++)
{
cin >> g.head[i].data;
g.head[i].next = NULL;
}
for (int i = 0; i < g.en; i++)
{
cout << "Input the vertexs of the edge" << endl;
int a, b;
cin >> a >> b;
Node* temp = (Node*)malloc(sizeof(Node));
//头插法插入边
*temp = { Located(g,b),g.head[Located(g, a)].next};
g.head[Located(g, a)].next = temp;
}
}
//此处存放个顶点的入度数,与个顶点在数组中存放的下标位置对应
int InDegree[MAX_VERTEX];
void FindInDegree(Graph g)
{
for (int i = 0; i < g.vn; i++)
InDegree[i] = 0;
for (int i = 0; i < g.vn; i++)
for (Node* p = g.head[i].next; p; p = p->next)
InDegree[p->data]++;
}
//拓扑排序
void TopoLogicalSort(Graph g)
{
stack<int>s;
FindInDegree(g);
//将所有入度为0的顶点下标入栈
for (int i = 0; i < g.vn; i++)
if(!InDegree[i])
s.push(i);
while (!s.empty())
{
int v=s.top();
s.pop();
cout << g.head[v].data << " ";
//将该顶点周边一圈顶点的入度-1,若有减完入度为0的直接入栈
for (Node* p = g.head[v].next; p; p = p->next)
if (!(--InDegree[p->data]))
s.push(p->data);
}
}
int main()
{
Graph g;
CreateGraph(g);
TopoLogicalSort(g);
}
拓扑排序,图的邻接表存储,C++实现
于 2024-07-14 21:30:49 首次发布