拓扑序列的实现

来源:互联网 发布:怎样把nginx部署到公网 编辑:程序博客网 时间:2024/05/01 12:36
#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_DEBUGfreopen("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;}

0 0
原创粉丝点击