UVa 10305-ordering Tasks (topological sort nude)

Source: Internet
Author: User

John had n tasks to do. Unfortunately, the tasks independent and the execution of one task is only possible if and tasks with already be En executed.

Input

The input would consist of several instances of the problem. Each instance begins with a line containing the integers, 1 <= n <= and M. n is the number of the tasks (numbered from 1 to n) and m are the number of direct Preceden Ce relations between tasks. After this, there'll be m lines with II integers i and J, representing the fact that task i must be executed before task J. An instance with n = m = 0 would 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
Ideas:
Topological sort naked question, using the letter of the DFS on the purple Book

Implementation code:
#include <bits/stdc++.h>using namespacestd;Const intM = $;intx,y,n,m,vis[m],topo[m],g[m][m],t;BOOLDfsintu) {Vis[u]= -1;//currently in the judgment of the     for(inti =1; I <= N;i + +){        if(G[u][i]) {if(Vis[i] <0)return false; if(!vis[i]&&!dfs (i))return false; }} Vis[u]=1; topo[t--] =u; return true;}BOOLToposort () {T=N; memset (Vis,0,sizeof(VIS));  for(inti =1; I <= N;i + +)        if(!vis[i]&&!dfs (i))return false; return true;}intMain () { while(cin>>n>>m) {        if(n==0&&m==0) Break; Memset (g,0,sizeof(g));  while(m--) {cin>>x>>y; G[x][y]=1; }        if(Toposort ()) { for(inti =1; I <= N;i + +){                if(i==n) cout<<topo[i]<<Endl; Elsecout<<topo[i]<<" "; }        }    }    return 0;}

UVa 10305-ordering Tasks (topological sort naked)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.