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

来源:互联网 发布:mac 装google chrome 编辑:程序博客网 时间:2024/05/21 11:17

【度娘说】:

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

【实现】:




/*input:6 80 10 20 31 42 42 53 43 5output:V0 V3 V2 V5 V1 V4 */#include<iostream>#include<stdlib.h>using namespace std;#define EleType int#define MAX_NUM 100typedef 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;}




0 0
原创粉丝点击