UVA - 10305(拓扑排序)

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

题意: 约翰有n个任务要做。 不幸的是,任务不是独立的,而是执行一项任务只有在其他任务已经执行的情况下才有可能。

n是任务数(编号从1到n),m是任务之间直接优先关系的数量。 在此之后,将有m行具有两个整数i和j,表示任务i必须在任务j之前执行的事实。n = m = 0的实例将完成输入。对于每个实例,使用n个整数打印一行,以整个可能的执行顺序表示任务。

思路:裸的拓扑排序。。。。

#include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
const int maxn = 500+50;
int n, m, x, y, edge[maxn][maxn], in[maxn];
void topsort()
{
    priority_queue<int, vector<int>, greater<int> >q;
    for(int i = 1; i <= n; i++)
        if(in[i] == 0) q.push(i);
    int flag = 0, f;
    while(!q.empty())
    {
        f = q.top(); q.pop();
        if(flag) printf(" %d", f);
        else printf("%d",f); flag = 1;

        for(int i = 1; i <= n; i++)
        {
            if(edge[f][i] != 0)
            {
                in[i] -= edge[f][i];
                if(!in[i]) q.push(i);
            }
        }
    }

}
int main()
{
    while(~scanf("%d%d",&n,&m) && n+m)
    {
        mem(edge,0); mem(in,0);
        while(m--)
        {
            scanf("%d%d",&x,&y);
            edge[x][y]++; in[y]++;
        }
        topsort(); puts("");
    }
}

猜你喜欢

转载自blog.csdn.net/sugarbliss/article/details/81263708