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

【度娘说】:

对一个有向无环图(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[n].idegree;
            cout<<"V"<<n<<" ";

            //删除以出栈顶点为 尾 的边 的 头顶点 的 入度
            for(np = graph[n].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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PeersLee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值