拓扑排序,AOV网络,AOE网络

参考《图论算法理论,实现及应用》一书修改而来

拓扑排序:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAXN 10
struct ArcNode
{
    int to;
    struct ArcNode *next;
};
int n,m;
ArcNode* List[MAXN];
int count[MAXN];
char output[100];

void TopSort()
{
    int top=-1;
    ArcNode* tmp;
    bool bcycle=false;
    int pos=0;
    for(int i=1;i<=n;i++)
    {
        if(count[i]==0)
        {
            count[i]=top;
            top=i;
        }
    }
    for(int i=0;i<n;i++)
    {
        if(top==-1)
        {
            bcycle=true;
            break;
        }
        else
        {
            int j=top;
            top=count[top];
            pos+=sprintf(output+pos,"%d ",j);
            tmp=List[j];
            //遍历顶点j的边链表,每条出边的终点的入度减1
            while(tmp!=NULL)
            {
                int k=tmp->to;
                if(--count[k]==0)
                {
                    count[k]=top;top=k;
                }
                tmp=tmp->next;
            }
        }
    }
    if(bcycle)
        printf("Network has a cycle!\n");
    else
    {
        int len=strlen(output);
        output[len-1]=0;
        printf("%s\n",output);
    }
}

int main()
{
    int u,v;
    while(scanf("%d%d",&n,&m))<span style="white-space:pre">	</span>//n为点的个数,m为边的个数
    {
        if(n==0 && m==0)
            break;
        memset(List,0,sizeof(List));
        memset(count,0,sizeof(count));
        memset(output,0,sizeof(output));
        ArcNode* tmp;
        for(int i=1;i<=m;i++)//构造边链表
        {
            scanf("%d%d",&u,&v);//读入起点和终点
            count[v]++;
            tmp=new ArcNode;
            tmp->to=v;tmp->next=NULL;
            if(List[u]==NULL)
                List[u]=tmp;
            else
            {
                tmp->next=List[u];
                List[u]=tmp;
            }
        }

        TopSort();
        for(int i=0;i<n;i++)
        {
            tmp=List[i];
            while(tmp!=NULL)
            {
                List[i]=tmp->next;
                delete tmp;
                tmp=List[i];
            }
        }
    }
    return 0;
}


例子:

6 8
1 2
1 4
2 6
3 2
3 6
5 1
5 2
5 6
6 8
1 3
1 2
2 5
3 4
4 2
4 6
5 4
5 6
0 0
未完待续。。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值