ACM 之 M - Ordering Tasks

Description

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

Input

The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1 <= n <= 100 and m. n is the number of tasks (numbered from 1 to n) and m is the number of direct precedence relations between tasks. After this, there will be m lines with two integers i and j, representing the fact that task i must be executed before task j. An instance with n = m = 0 will finish the input.

Output

For each instance, print a line with n integers representing the tasks in a possible 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 namespace std;
int map[101][101],inde[101];
void topu(int a[101][101],int d[101],int n)
{
    int f=0;
    for(int i=0;i<n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(d[j]==0)
            {
                d[j]--;
                if(f==1)
                {cout<<" "<<j;}
                if(f==0)
                {
                    cout<<j;
                    f=1;
                }
                for(int k=1;k<=n;k++)
                {
                    if(a[j][k]==1)
                    {
                        d[k]--;
                    }
                }
            }
        }
    }
}
int main()
{
    int m,n;
    while(cin>>m>>n)
    {
        if(m==0&&n==0)
            return 0;
        int a,b;
        memset(map,0,sizeof(map));
        memset(inde,0,sizeof(inde));
        for(int i=1;i<=n;i++)
        {
            cin>>a>>b;
            if(!map[a][b])
            {
                map[a][b]=1;
                inde[b]++;
            }
        }
        topu(map,inde,m);
        cout<<endl;
    }
    return 0;
}

意见反馈 || 任何建议

联系我(新浪)
邮箱:qianlizhihao@gmail.com

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 心理学家武志红在他的公众号的一篇文章,分析原生家庭与婚姻情感的关系,剖析《道德颂》这本书。 从图书馆借了书,两天内...
    庄心爱写作阅读 738评论 3 3
  • 反向传值   在开发中我们经常会遇到将当前视图控制中的某些值传到另一个视图控制器,下面将介绍常用的几种反向传值的方...
    pingui阅读 904评论 0 1
  • 昨日见了一个老友,高中同学,在高中时旁人说起我便会想起她的那种好。 毕业她出国,我去了云南,相隔千里,...
    一尾羊阅读 311评论 0 1