zoukankan      html  css  js  c++  java
  • 拓扑排序

    邻接矩阵:

    View Code
    #include <iostream>
    #include <stdio.h>
    using namespace std;
    #define E 1001
    void Topsort(int count[],int n,int edge[][E])
    {
        int i,top=-1;
        for(i=0;i<n;i++)
            if(count[i]==0)
            {
                count[i]=top;
                top=i;
            }
        for(i=0;i<n;i++)
            if(top==-1)
            {
                printf("0 degree stack is empty,there are cycles in graph\n");
                return ;
            }
            else
            {
                int j=top;
                top = count[j];
                printf("%d->",j);
                for(int k=0;k<n;k++)
                    if(edge[j][k])
                    {
                        count[k]--;
                        if(count[k]==0)
                        {
                            count[k]=top;
                            top=k;
                        }
                    }
            }
    }
    int main()
    {
        return 0;
    }

    邻接表:

    View Code
    #include <iostream>
    #include <stdio.h>
    using namespace std;
    #include <string.h>
    #define E 10000
    struct edge
    {
        int s,t,next;
    };
    int head[E];
    void Topsort(int count[],int n,edge e[])
    {
        int top=-1;
        for(int i=0;i<n;i++)
        {
            if(count[i]==0)
            {
                count[i]=top;
                top=i;
            }
        }
        for(int i=0;i<n;i++)
        {
            if(top==-1)
            {
                printf("0 degree stack is empty,there are cycles in graph\n");
                return ;
            }
            else
            {
                int j=top;
                top=count[j];
                printf("%d->",j);
                for(int k=head[j];k!=-1;k=e[k].next)
                {
                    if((--count[e[k].t])==0)
                    {
                        count[e[k].t]=top;
                        top=e[k].t;
                    }
                }
            }
        }
    }
    int main()
    {
        return 0;
    }

    思想:

    维护一个顶点入度为0的栈,

    每次取栈顶元素top输出,对于top相邻的点进行入度数-1处理,处理后如果度数为0,再次入栈.

    执行n次出栈操作,便可输出一个图的拓扑序.

    判断是否包含有向环:如果入度为0的栈为空(top==-1),则说明包含有向环.(证明:无环时总有点入度为0).

    时间复杂度:

    1.搜索入度为0的顶点,建栈所需时间O(n);

    2.无有向环时,每个顶点入栈一次,出栈一次,每条边扫描一次且仅一次,时间复杂度O(m).

    3.总复杂度:O(n+m).

  • 相关阅读:
    2021软件工程-个人阅读作业
    OO第四单元——基于UML的UML解析器总结&OO课程总结
    OO第三单元——基于JML的社交网络总结
    OO第二单元——电梯作业总结
    SQL拼接字符串
    SQL查询列表中每种类型的第一条
    JS获取当前时间,设置不可用以前的时间
    JavaScript中的函数使用
    .Net软件开发面试技巧
    .Net小白的第一篇博客
  • 原文地址:https://www.cnblogs.com/markliu/p/2518129.html
Copyright © 2011-2022 走看看