数据结构 — 图 之 拓扑排序 (AOV网)
2015-11-26 16:59
453 查看
【度娘说】:
对一个有向无环图(Directed
Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边(u,v)∈E(G),则u在线性序列中出现在v之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这个操作称之为拓扑排序。
【实现】:
对一个有向无环图(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; }
相关文章推荐
- 数据结构(Java)——优先队列和堆
- SDUT 3364-数据结构实验之图论八:欧拉回路(并查集)
- SDUT 3363-数据结构实验之图论七:驴友计划(最短路_dijkstra)
- SDUT 3362-数据结构实验之图论六:村村通公路(最小生成树_prim)
- SDUT 3361-数据结构实验之图论四:迷宫探索(dfs)
- 《大话数据结构》之Prim算法
- 文章标题
- 数据结构与算法(1)——分解质因数及各种方法求最大公约数
- 《大话数据结构》之广度优先遍历
- 《大话数据结构》之图的深度优先遍历
- 数据结构实验之图论八:欧拉回路
- 数据结构实验之图论四:迷宫探索
- 【数据结构】 栈的应用举例(3例)——更好的学习和理解栈
- 数据结构之二叉树详说
- 数据结构之堆(java)
- 数据结构实验之图论四:迷宫探索
- 【2015/11/21】 数据结构学习日志_Day17 双端链表
- leetcode之Rotate Array
- redis数据结构-链表
- 双向链表