Problem

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

문제 풀이

위상 정렬의 기분 문제이다.
dfs를 이용해서 위상 정렬로 풀었다.

답안 코드

#include <cstdio>
#include <vector>
#include <cstring>

using namespace std;

#define MAX_N   100+1

int n, m;
vector<int> adj[MAX_N];
vector<int> ts;
bool visited[MAX_N];

void dfs(int u){
    visited[u] = true;
    for(int i = 0; i < adj[u].size(); ++i){
        int v = adj[u][i];
        if(!visited[v])
            dfs(v);
    }
    ts.push_back(u);
}

int main(){
    while(true){
        scanf("%d %d\n", &n, &m);
        if(n == 0)  break;
        
        int a,b;
        for(int i = 0; i < m; ++i){
            scanf("%d %d\n", &a,&b);
            adj[a].push_back(b);
        }
        
        for(int i = 1; i <= n; ++i)
            if(!visited[i])
                dfs(i);
        
        for(int i = (int)ts.size()-1; i >= 0; --i){
            printf("%d ", ts[i]);
        }
        printf("\n");
        
        memset(visited,false,sizeof(visited));
        ts.clear();
        for(int i = 0; i < n; ++i)
            adj[i].clear();
    }
    return 0;
}

문제 위치 – https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=15&page=show_problem&problem=1246