拓扑排序

#include<iostream>
#include<cstdlib>
#include<cstring> 
using namespace std;
#define maxSize 100
//边表
typedef struct ArcNode  
{
	int adjvex;                //该边所指向的结点的位置 
	struct ArcNode *nextarc;   //指向下一条边的指针 
	int info;                  //该边的相关信息(如权值) 
}ArcNode;
//顶点表
typedef struct   
{
	char data; 				   //顶点信息
	int count;                 
	ArcNode *firstarc;         //指向第一条边的指针 
}VNode;
typedef struct
{
	VNode adjlist[maxSize];    //邻接表 
	int n,e;                   //顶点数和边数 
}AGraph;
void Create(AGraph *G)
{ 
    cout<<"请输入顶点数和边数:"<<endl;
	cin>>G->n>>G->e;
	cout<<"输入顶点信息:"<<endl;
	for(int i=0;i<G->n;i++)                 
	{
		getchar();
		cin>>G->adjlist[i].data;
		G->adjlist[i].firstarc=NULL; //指向边表的指针初始时置为空 
		G->adjlist[i].count=0;
    }
    ArcNode *p;
	//建立边表
	cout<<"输入边的下标:"<<endl;
	for(int k=0;k<G->e;k++)                    
	{
		int i,j;
		cin>>i>>j;
		G->adjlist[j].count++;
   		p=(ArcNode*)malloc(sizeof(ArcNode)); 
		p->adjvex=j; 						  //存储弧头 
		p->nextarc=G->adjlist[i].firstarc;    //头插法插入边结点 
		G->adjlist[i].firstarc=p;			    
	}
}
int TopSort(AGraph *G)
{
	int i,j,n=0;
	int stack[maxSize],top=-1;
	ArcNode *p;
	for(i=0;i<G->n;++i)
		if(G->adjlist[i].count==0)
			stack[++top]=i;
	while(top!=-1)
	{
		i=stack[top--];
		++n;
		cout<<i<<" ";
		p=G->adjlist[i].firstarc;
		while(p!=NULL)
		{
			j=p->adjvex;
			--(G->adjlist[j].count);
			if(G->adjlist[j].count==0)
				stack[++top]=j;
			p=p->nextarc;
		}
	}
	if(n==G->n)
		return 1;
	else 
		return 0;
}
/* 
7 11
a b c d e f g
0 1 0 2 0 3
1 2 1 4 2 5 2 4
3 5 4 6 5 4 5 6
*/
int main()
{
	AGraph G;
	Create(&G);
	TopSort(&G);
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值