美文网首页C++
ACM 之 M - Ordering Tasks

ACM 之 M - Ordering Tasks

作者: Gadore千里 | 来源:发表于2016-07-21 18:23 被阅读121次

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

相关文章

网友评论

    本文标题:ACM 之 M - Ordering Tasks

    本文链接:https://www.haomeiwen.com/subject/cxwbjttx.html