uva 10305 - Ordering Tasks

Problem F

Ordering Tasks

Input: standard input

Output: standard output

Time Limit: 1 second

Memory Limit: 32 MB

 

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 <stack>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <stack>
#include <list>
#include <sstream>
#include <cmath>

using namespace std;

#define ms(arr, val) memset(arr, val, sizeof(arr))
#define mc(dest, src) memcpy(dest, src, sizeof(src))
#define N 105
#define INF 0x3fffffff
#define vint vector<int>
#define setint set<int>
#define mint map<int, int>
#define lint list<int>
#define sch stack<char>
#define qch queue<char>
#define sint stack<int>
#define qint queue<int>

int ans[N], in[N], out[N], g[N][N], p;
void init()
{
    p = 0;
    ms(in, 0);
    ms(out, 0);
    ms(g, 0);
}
qint qi;
int main()
{
    int n, m, s, e;
    while (scanf("%d%d", &n, &m), n)//m可以为0
    {
        init();
        while (m--)
        {
            scanf("%d%d", &s, &e);
            in[e]++;
            out[s]++;
            g[s][e] = 1;
        }

        for (int i = 1; i <= n; i++)
        {
            if (!in[i] && !out[i])
            {
                ans[p++] = i;
            }
            else
                if (!in[i])
                {
                    qi.push(i);
                }
        }
        while (!qi.empty())
        {
            s = qi.front();
            ans[p++] = s;
            qi.pop();
            for (e = 1; e <= n; e++)
            {
                if (g[s][e])
                {
                    g[s][e] = 0;
                    in[e]--;
                    if (!in[e])
                    {
                        qi.push(e);
                    }
                }
            }
        }
        printf("%d", ans[0]);
        for (s = 1; s < p; s++)
        {
            printf(" %d", ans[s]);
        }
        putchar('\n');
    }
    return 0;
}

 

posted on 2014-08-15 13:53  jec  阅读(429)  评论(0编辑  收藏  举报

导航