拓扑排序、

#include <iostream>
#include <stack>
using namespace std;
#define MAX_VERTEX_NUM 26
typedef struct ArcNode{
        int adjvex;
        struct ArcNode *nextarc;
        ArcNode(){nextarc=NULL;}
}ArcNode;//链表中的节点 
typedef struct VNode{
//        int data;
        ArcNode *firstarc;
        VNode(){firstarc=NULL;}
}VNode,AdjList[MAX_VERTEX_NUM];//图数组和单数组节点 
typedef struct{
        AdjList vertices;
        int vexnum,arcnum;
}ALGraph;//保存整个图结构的信息
ALGraph graph;
int in_degree[MAX_VERTEX_NUM];
void CreatGraph(){
	cin>>graph.vexnum>>graph.arcnum;
	for(int i=0;i<graph.arcnum;i++){
		ArcNode *temp1=new ArcNode;
	//	ArcNode *temp2=new ArcNode;
		int x,y;cin>>x>>y;
		temp1->adjvex=y;temp1->nextarc=NULL;
	//	temp2->adjvex=x;temp2->nextarc=NULL;
		if(!graph.vertices[x].firstarc) graph.vertices[x].firstarc=temp1;
		else{
			temp1->nextarc=graph.vertices[x].firstarc;
			graph.vertices[x].firstarc=temp1;
		}
	/*	if(!graph.vertices[y].firstarc) graph.vertices[y].firstarc=temp2;
		else{
			temp2->nextarc=graph.vertices[y].firstarc;
			graph.vertices[y].firstarc=temp2;
		}*/
	//	in_degree[x]++;
		in_degree[y]++;
	}
}
void TopologicalSort()
{
	stack<int> S;
	for(int i=1;i<=graph.vexnum;i++){if(!in_degree[i]) S.push(i);}
	while(!S.empty()){
		int i=S.top();S.pop();
		cout<<i<<" ";
		ArcNode *temp=graph.vertices[i].firstarc;
		while(temp){
			in_degree[temp->adjvex]--;
			if(!in_degree[temp->adjvex]) S.push(temp->adjvex);
			temp=temp->nextarc;
		}
	}
}
int main(void){
	CreatGraph();
	TopologicalSort();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值