10305 - Ordering Tasks

John has n tasksto do. Unfortunately, the tasks are not independent and the execution of onetask is only possible if other tasks have already been executed.

Input

The input willconsist of several instances of the problem. Each instance begins with a linecontaining two integers, 1 <= n <= 100 and mn isthe number of tasks (numbered from 1 to n)and m is the number of direct precedence relations betweentasks. After this, there will be m lines with twointegers i and j, representing the fact that task i mustbe executed before task j. An instance with n = m = 0 willfinish the input.

Output

For each instance,print a line with n integers representing the tasks in apossible order of execution.

Sample Input

5 4

1 2

2 3

1 3

1 5

0 0

Sample Output        

1 4 2 5 3

代码:

#include<iostream>

#include<cstring>

using namespacestd;

 

const intmaxn=1000;

int G[maxn][maxn];//若(u,v)则将G[u][v]变为1

int topo[maxn];//存储拓扑排序后的结果

int n,m;

int temp;

int c[maxn];

/*

标记某结点是否被访问:0表示未被访问;-1表示正在被访问;1表示访问完毕

*/

 

bool  toposort();

bool dfs(int u);

 

int main()

{

    while(cin>>n>>m&&n)

    {

        memset(G,0,sizeof(G));

        memset(topo,0,sizeof(topo));

        int a,b;

        for(int i=0; i<m; i++)

        {

            cin>>a>>b;

            a--;//从0—N-1存储

            b--;

            G[a][b]=1;

        }

        if(toposort())

        {

            for(int i=0; i<n-1; i++)

            {

               cout<<topo[i]+1<<" ";//还原+1

            }

           cout<<topo[n-1]+1<<endl;

        }

    }

    return 0;

}

 

bool toposort()

{

    temp=n;

    memset(c,0,sizeof(c));//每组数据都要清空

    for(int i=0; i<n; i++)

    {

        if(!c[i])//若该节点没被访问过

        {

            if(!dfs(i))//若该图存在有向环

            {

                return false;

            }

        }

    }

    return true;

}

 

bool dfs(int u)

{

    c[u]=-1;//正在被访问

    for(int v=0;v<n;v++)

    {

        if(G[u][v])//存在优先关系

        {

            if(c[v]==-1)//存在有向环

            {

                return false;

            }

            if(c[v]==0)

            {

                dfs(v);//深搜

            }

        }

    }

    c[u]=1;//访问完毕

    topo[--temp]=u;

    return true;

}

题意:

把每个变量看成一个点,“小于”看成有向边,则得到一个有向图;将该图的所有节点排序,使得每一条有向边(u,v)对应的u都排在v的前面。若存在有向环,则不存在拓扑排序。只有有向无环图可以进行拓扑排序。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值