拓扑排序,图的邻接表存储,C++实现

//拓扑排序
//主要思路:只能输出入度为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);
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值