拓扑排序

来源:互联网 发布:放到网络上的英文 编辑:程序博客网 时间:2024/05/16 03:17
#include <iostream>#include <cstdio>#include <cstring>using namespace std;#define maxn 105int n,m,t;int a[maxn][maxn];int vis[maxn],des[maxn];bool dfs(int u){    vis[u]=-1;    for(int i=1; i<=n; i++)        if(a[u][i])    {        if(vis[i]==-1) return false;    else if(!vis[i]&&!dfs(i)) return false;    }    vis[u]=1;    des[--t]=u;    return true;}int main(){    while(~scanf("%d%d",&n,&m)&&n+m)    {        t=n;        memset(a,0,sizeof(a));        memset(vis,0,sizeof(vis));        int p,q;        for(int i=0; i<m; i++)        {            cin>>p>>q;            a[p][q]=1;        }        for(int i=1; i<=n; i++)         if(!vis[i])             dfs(i);        for(int i=0; i<n; i++)        {            if(!i) cout<<des[i];            else cout<<" "<<des[i];        }        cout<<endl;    }    return 0;}

1 0
原创粉丝点击