您的位置:首页 > 理论基础 > 数据结构算法

数据结构 — 图 之 拓扑排序 (AOV网)

2015-11-26 16:59 453 查看
【度娘说】:

对一个有向无环图(Directed
Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边(u,v)∈E(G),则u在线性序列中出现在v之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这个操作称之为拓扑排序。

【实现】:



/*
input:

6 8
0 1
0 2
0 3
1 4
2 4
2 5
3 4
3 5

output:
V0 V3 V2 V5 V1 V4

*/

#include<iostream>
#include<stdlib.h>

using namespace std;

#define EleType int
#define MAX_NUM 100

typedef struct node {
EleType v;
struct node *next;
}NodeType,*NodePointer;

typedef struct {
int idegree;
NodePointer next;
}GNode,*GPointer;

GNode graph[MAX_NUM];
int vn,en;  //顶点数和边数

void CreatG() {

EleType et1,et2;
NodePointer tail;
cin>>vn>>en;

for(int i = 0; i<vn; i++) {
graph[i].idegree = 0;
graph[i].next = NULL;
}

for(int i = 0; i<en; i++) {
cin>>et1>>et2;

NodePointer np = new NodeType;
np->v = et2;
np->next = NULL;

if(graph[et1].next == NULL) {
graph[et1].next = np;
}else {
tail = graph[et1].next;
while(tail->next != NULL ) {
tail = tail->next;
}
tail->next = np;
}

graph[et2].idegree++;
}

}

void TopSort() {
int n,m;
int top;

NodePointer np;

top = -1;
for(int i = 0; i<vn; i++) {
//入栈
if(graph[i].idegree == 0) {
graph[i].idegree = top;
top = i;
}
}

//topsort
for(int i = 0; i<vn; i++) {
//如果已经到了栈底说明图中包含环路
if (top == -1) {
cout<<"图中有环路,工程不可行"<<endl;
exit(1);
}else {
//出栈
n = top;
top = graph
.idegree;
cout<<"V"<<n<<" ";

//删除以出栈顶点为 尾 的边 的 头顶点 的 入度
for(np = graph
.next; np; np = np->next) {
m = np->v;
graph[m].idegree--;
if(graph[m].idegree == 0) {
graph[m].idegree = top;
top = m;
}
}
}
}
cout<<endl;
}

int main() {
CreatG();
TopSort();

return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: