拓扑序列的实现

#include <cstdio>
#include <stack>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

struct Edge {
    int from,to,next;
};
const int maxn=100;
const int maxm=maxn*maxn;

int m,n;//n个顶点,m条边
int pre[maxn];//pre[i]表示顶点从i出发的最后一条边的编号
Edge edge[maxm];//存储边
int edgeNum=0;//边的数量

int dcount[maxn];//度数数组
stack<int> deg;// 度数栈
vector<int> ans;// 结果

int main()
{
#ifdef LOCAL_DEBUG
freopen("input.txt","r",stdin);
#endif // LOCAL_DEBUG
    while(scanf("%d%d",&n,&m) && n+m )
    {
        //初始化
        memset(pre,-1,sizeof(pre));
        memset(dcount,0,sizeof(dcount));
        while(!deg.empty()) deg.pop();
        ans.clear();
        edgeNum=0;

        //构造边集
        int from,to;
        for(int i=1;i<=m;i++) {
            scanf("%d%d",&from,&to);
            dcount[to]++;
            edge[edgeNum].from=from;
            edge[edgeNum].to=to;
            edge[edgeNum].next=pre[from];
            pre[from]=edgeNum;
            edgeNum++;
        }
        //top算法实现
        for(int i=1;i<=n;i++) {
            if(!dcount[i])
                deg.push(i);
        }
        if(deg.empty()) {
            printf("Network has a cycle!\n"); continue;
        }
        int topNum=0;
        while(!deg.empty())
        {
            int t=deg.top(); deg.pop();
            topNum++;
            ans.push_back(t);
            for(int k=pre[t];k!=-1;k=edge[k].next) //遍历边
            {
                int x=edge[k].to;
                dcount[x]--;
                if(dcount[x]==0) {
                    deg.push(x);
                }
            }
        }
        if(topNum<n) {
            printf("Network has a cycle!\n"); continue;
        }
        else {
            for(int i=0;i<n-1;i++) {
                printf("%d ",ans[i]);
            }
            printf("%d\n",ans[n-1]);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值