UVA - 10305 - Ordering Tasks (拓扑排序!)

UVA - 10305

Ordering Tasks
Time Limit: 3000MS Memory Limit: Unknown 64bit IO Format: %lld & %llu

Submit Status

Description

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 mn 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

(The Joint Effort Contest, Problem setter: Rodrigo Malta Schmidt)

Source

Root :: Competitive Programming 3: The New Lower Bound of Programming Contests (Steven & Felix Halim) :: Graph :: Graph Traversal ::  Topological Sort
Root :: Competitive Programming 2: This increases the lower bound of Programming Contests. Again (Steven & Felix Halim) :: Graph :: Graph Traversal ::  Topological Sort
Root :: AOAPC II: Beginning Algorithm Contests (Second Edition) (Rujia Liu) :: Chapter 6. Data Structures ::  Examples
Root :: AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 2. Data Structures ::  Graphs

Root :: Competitive Programming: Increasing the Lower Bound of Programming Contests (Steven & Felix Halim) :: Chapter 4. Graph :: Depth First Search ::  Topological Sort

白书上的拓扑排序!


AC代码:


#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int flag, n, m;
int topo[110], num[110], s[110][110];

bool dfs(int site)
{
    num[site]=-1;
    for(int i=1; i<=n; i++)
        if(s[site][i]&&(num[i]<0||(!num[i]&&!dfs(i)))) return false;
    num[site]=1;
    topo[--flag]=site;
    return true;
}

bool toposort()
{
    flag=n;
    memset(num,0,sizeof(num));
    for(int i=1; i<=n; i++)
        if(!num[i]&&!dfs(i)) return false;
    return true;
}

int main()
{
    int x,y,count;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(!n&&!m) break;
        memset(s,0,sizeof(s));
        for(count=0; count<m; count++)
        {
            scanf("%d%d",&x,&y);
            s[x][y]=1;
        }
        if(toposort())
            for(count=0; count<n-1; count++) printf("%d ",topo[count]);
        printf("%d\n",topo[count]);
    }
    return 0;
}



你可能感兴趣的:(数据结构,图论,拓扑排序,DFS,uva)