• 邻接表拓扑排序




    测试所用图如下:



    #include<stdio.h>
    #include<iostream>
    #include<string.h>
    #include<string>
    #include<cmath>
    #include<vector>
    #include<set>
    #define OK 1
    #define ERROR 0
    using namespace std;
    typedef struct NODE{
    int adjvex;
    int weight;
    NODE *next;
    }node;
    
    typedef struct {
    int in;
    int data;
    NODE *first;
    }nodeList;
    
    typedef struct {
    int num_vex;
    int num_edge;
    nodeList headvex[100];
    }Graph;
    void create(Graph *g){
    scanf("%d%d",&g->num_vex,&g->num_edge);
    int i,j,x,y,z;
    for(i=0;i<g->num_vex;i++)
    {scanf("%d",&g->headvex[i].data);
    g->headvex[i].in=0;
    g->headvex[i].first=NULL;
    }
    //相比普通邻接表,拓扑排序的邻接表只是在每个表头节点多加了一个表示入度的值(即是in)
    node *e;
    for(i=0;i<g->num_edge;i++){
        scanf("%d%d%d",&x,&y,&z);
        e=new NODE();
        e->weight=z;
        e->adjvex=y;
        g->headvex[y].in++;
        e->next=g->headvex[x].first;
        g->headvex[x].first=e;
    }
    
    }
    int TopologicalSort(Graph *g){
    NODE *e;
    int i,j,k,gettop;
    int mystack[100];
    int top=0;
    int Count=0;
    //top mystack gettop 用来模拟栈
    for(i=0;i<g->num_vex;i++)
    {
        if(g->headvex[i].in==0)
        mystack[++top]=i;//遍历邻接表表头节点,将入度为零的结点首先入栈
    }
    while(top!=0){//如果栈不为空,while循环继续
    gettop=mystack[top--];//出栈
    printf("%d ",g->headvex[gettop].data);
    Count++;
    for(e=g->headvex[gettop].first;e;e=e->next)
        {
            g->headvex[e->adjvex].in--;//删去被出栈节点所连的边,即是把与此节点邻接的点的入度减一
            if(g->headvex[e->adjvex].in==0)mystack[++top]=e->adjvex;//把入度为0的点入栈
        }
    }
    printf("
    ");
    if(Count<g->num_vex)//如果count小于总结点数,说明不是aov网图
    return ERROR;
    else return OK;
    }
    int main(){
    
    int i,j,k;
    Graph G;
    create(&G);
    k=TopologicalSort(&G);
    
    printf("ans:%d
    ",k);
    
    return 0;
    }
    /*
    14 20
    0 1 2 3 4 5 6 7 8 9 10 11 12 13
    0 4 1
    0 5 1
    0 11 1
    1 4 1
    1 8 1
    1 2 1
    2 5 1
    2 6 1
    2 9 1
    3 2 1
    3 13 1
    4 7 1
    5 8 1
    5 12 1
    6 5 1
    8 7 1
    9 10 1
    9 11 1
    10 13 1
    12 9 1
    */
    


    测试图转换成邻接表如下:



  • 相关阅读:
    程序用windows快捷键
    vc6中如何加入BMP图片资源
    vc 中解析字符串
    视频压缩编码问与答
    ActiveX and Com
    Windows 2000 IIS 安装、配置.WEB篇
    javascript 如何调用activex的方法和属性
    bmp 转为jpg
    Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0
    几种DC及区别
  • 原文地址:https://www.cnblogs.com/hjch0708/p/7554824.html
Copyright © 2020-2023  润新知