Ordering Tasks 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
拖补排序:先将入度为0的点加入队列,然后去除这些点,这些点对应的源点的度减一若为0加入队列。
AC的C++程序如下:

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
using namespace std;
const int maxn = 105;
int into[maxn], order[maxn];
vector<int> g[maxn];
int n, m;
int main()
{
    while (cin>>n>>m)
    {
        if (m == 0 && n == 0) break;
        int src, dest;
        queue<int> q;
        memset(into, 0, sizeof(into));
        for (int i = 0; i <= n; i++) g[i].clear();
        for (int i = 0; i < m; i++)
        {
            cin >> src >> dest;
            into[dest]++;
            g[src].push_back(dest);
        }
        int len = 0;
        for (int i = 1; i <= n; i++)
        {
            if (into[i] == 0) q.push(i);
        }
        while (!q.empty())
        {
            int front = q.front();
            q.pop();
            order[len++] = front;
            for (int i = 0; i < g[front].size(); i++)
            {
                into[g[front][i]]--;

                if (into[g[front][i]] == 0) q.push(g[front][i]);
            }
        }
        for (int i = 0; i <len; i++)
        {
            if (i != 0) cout << " ";
            cout << order[i];
        }
        cout << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/jinduo16/article/details/81744988