uva10305 拓扑排序经典dfs

来源:互联网 发布:淘宝网购手机怎么保修 编辑:程序博客网 时间:2024/06/08 14:57
#include<stdio.h>#include<string.h>#define maxx 100+5int mapp[maxx][maxx],topo[maxx],c[maxx];int n,t;int dfs(int u){    int v;    c[u]=-1;    for(int v=1;v<=n;v++)    {        if(mapp[u][v])        {            if(c[v]<0)                return 0;            else if(c[v]==0&&dfs(v)==0)                return 0;        }    }    c[u]=1;    topo[t--]=u;    return 1;}int toposort(){    int i;    t=n;    memset(c,0,sizeof(c));    for(i=1;i<=n;i++)        if(c[i]==0&&dfs(i)==0)        return 0;    return 1;}int main(){    int m,i;    while(scanf("%d%d",&n,&m)!=EOF&&m||n)    {        int a,b;        memset(mapp,0,sizeof(mapp));        while(m--)        {            scanf("%d%d",&a,&b);            mapp[a][b]=1;        }        if(toposort())        {            for( i=1;i<n;i++)                printf("%d ",topo[i]);            printf("%d\n",topo[i]);        }    }    return 0;}

0 0
原创粉丝点击