26.基于 有向图的邻接表表示 实现 AOV网 的拓扑排序


#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
using namespace std;
typedef int ElemType;
FILE *fp;
void InitFile()
{
	bool e;
	fopen_s(&fp, "data.txt", "r");
	if (!fp) exit(ERROR);
	return;
}
typedef bool Status;


/******
file input:
6
1 2
3 4
1 4
3 2
2 5
5 6
4 6
0 0

*******/



// 26.基于 有向图的邻接表表示 实现 AOV网 的拓扑排序

typedef struct node
{
	int vertex;//在head节点中 vertex表示节点邻接到该点的数量(也就是该点的入度)  也就是该点的出度count,在邻接表中 表示对应结点的标号.
	struct node *link;

}Node, *node_ptr, *Head_ptr;


int ver_num;
Head_ptr vertex;


Status InitGraph()
{
	int a, b, n;//n个节点   对应  1.......n
	fscanf_s(fp, "%d", &n);
	ver_num = n;
	vertex = (node_ptr)malloc(sizeof(Node)*(n + 1));
	if (!vertex) exit(ERROR);
	for (int i = 0; i <= n; i++){ vertex[i].vertex = 0; vertex[i].link = NULL; }
	while (fscanf_s(fp, "%d %d", &a, &b) && a && b)
	{
		if (a<1 || a>n || b<1 || b>n)  exit(ERROR);
		node_ptr  c;
		if (!(c = (node_ptr)malloc(sizeof(Node)))) exit(ERROR);
		c->vertex = b;
		c->link = vertex[a].link;
		vertex[a].link = c;
		vertex[b].vertex++;
	}
	return OK;
}

void Output_node(node_ptr t)
{
	printf("----> %d ", t->vertex);
	//if (!t->link) putchar(10);
}
void OutputGraph()
{
	printf("节点个数为%d :从 1 到 %d\n", ver_num, ver_num);
	printf("邻接表表示如下:\n");
	int n = ver_num;
	for (int i = 1; i <= n; i++)
	{
		printf("\nnode : %d :  (%d)  ", i, vertex[i].vertex);
		node_ptr t = vertex[i].link;
		while (t)
		{
			Output_node(t);
			t = t->link;
		}
	}
	printf("\n");
}

queue<int> Q;
int flag = 1;
Status topsort()
{
	node_ptr temp;
	int *marked = (int *)malloc(sizeof(int)*(ver_num + 1));
	if (!marked) return ERROR;
	//memset(marked, 0, sizeof(marked));
	for (int i = 1; i <= ver_num; i++) marked[i] = 0;
	int top = -1, t;
	for (int i = 0; i < ver_num; i++)
	{
		t = 1;
		while (t <= ver_num)
		{
			if (vertex[t].vertex == 0 && !marked[t])
			{
				top = t; break;
			}
			t++;
		}

		//top = t;

		if (top == -1) { flag = 0; break; }
		Q.push(top); marked[top] = 1;
		temp = vertex[top].link;
		while (temp)
		{
			vertex[temp->vertex].vertex--;
			temp = temp->link;
		}
		top = -1;
	}


	return OK;
}

//by zhaoyang @ 2014.4.21
int main()
{
	InitFile();

	InitGraph();
	OutputGraph();


	topsort();
	int t;
	if (flag){
		printf("存在一种拓扑排序为:\n");
		while (!Q.empty())
		{
			t = Q.front(); Q.pop();
			printf("----> %d ", t);
		}
		printf("\n");
	}
	else printf("存在有向环路,不存在拓扑序\n");



	fclose(fp);
	return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值