拓扑排序

邻接矩阵:

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).

原文地址:https://www.cnblogs.com/markliu/p/2518129.html