"VJ Job" "Topological sorting classic comprehension problem" ordering Tasks 1, Kahn algorithm; 2, DFS-based algorithm.

Source: Internet
Author: User

2018-02-13

links Https://cn.vjudge.net/contest/211129#problem/D

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≤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 would be m lines with II integers I and J, representing the fact that task I must be executed before TAS K J. An instance with n = m = 0 would? nish 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

Feelings:

just started to learn the topology sort, learned the following two ways to do this classic simple problem: 1, Kahn algorithm, 2, DFS-based algorithm (more than used). To tell the truth, fully understand spent a night a morning, the realization is basically also with other people's implementation is not bad, although very do not like so not independent to do the problem, but the fact that the level is not yet, is just learning it ... When to do what, learn to have a method, how to learn to be efficient, still groping ... It is said that both the complexity of the same is O (V+e), before the calculation of the complexity of a lot of misunderstanding, and now began to encounter an algorithm on their own calculation, slowly understand it, but also to cultivate the habit of calculating the complexity before the problem, at the same time to facilitate the problem. It's going to be pretty much. The complexity of all the algorithms will be sorted out.

Kahn Code:

     /*Topological sorting*/#include<cstdio>#include<cstring>#include<vector>#include<queue>// using namespacestd; Const intN = the; intN,m,son[n],toposort[n],t;//son is used to store the Toposort, as the name implies, the sequence that holds the title.Charo[2*N]; Vector<int>G[N];//vector associated Vertex g[n] The next thing to do is break the arc.  voidinit () { for(intI=1; i<=n; ++i)      {g[i].clear (); } memset (son,0,sizeof(son)); }    intMain () {intu,v;  while(SCANF ("%d%d", &n,&m) &&n+m)          {init ();  for(intI=0; i<m; ++i) {//The initial values of these places I are not random, be careful, always wrongscanf"%d%d",&u,&v);              G[u].push_back (v); ++Son[v]; }          intnum=N; Queue<int>q;//FIFO , like queuing, the first element to go out of a data structure.          for(intI=1; i<=n; ++i) {              if(!son[i]) Q.push (i);//pushes the 0-in point into the stack        }          intpos=0;  while(!q.empty ()) {//Empty to determine if the container is empty, and if NULL returns True here is the time for non-null execution while            intt=Q.front ();              Q.pop (); Toposort[pos++] =T;  for(intv=0; V<g[t].size (); ++V)//Broken arc Note notation                if(--son[g[t][v]]==0) Q.push (G[t][v]); //the complexity of the Kahn is O (n+m) is actually the linear order of N plus the number of arcs (that is, the number of cycles in the innermost loop, this is m)        }           for(intI=0; i<pos; ++i) {              if(!i) printf ("%d", Toposort[i]); Elseprintf"%d", Toposort[i]); } printf ("\ n"); }      return 0; }  

DFS-based algorithms (use recursion to determine if it is a dag)

#include <string.h>#include<cmath>#include<cstdio>#include<algorithm>#include<iostream>#include<vector>#include<queue>using namespacestd;intn,m;intvis[ the];//Markinttopo[ the]; intg[ the][ the];intT;BOOLDfsintu) {Vis[u]=-1;//Indicates that Access 1 indicates that a 0 has been accessed that has not been accessed     for(intv=1; v<=n;v++)    {        if(G[u][v]) {if(vis[v]==-1)return false;//If there is a forward ring, the failure exits            if(!vis[v]&&!dfs (v))return false;//! VIS[V] is to test whether this point has been visited has been visited no DFS or will be repeated to save the actual effect is to omit an if, think for a long time alas}//you can write that later .} Vis[u]=1; topo[--t]=u; return true;}BOOLToposort () {T=N; memset (Vis,0,sizeof(VIS));  for(intu=1; u<=n;u++)    {        if(!vis[u]&&!dfs (U))return false;//only Vis[u] is 0 o'clock Dfs and there is a ring when the return is false vis[u]=1 description has been visited not DFS to avoid changing the value of Vis            }    return true;} intMain () {intb;  while(~SCANF ("%d%d", &n,&m) &&m+n)//Note that the end condition entered there cannot be n&&m, because m may be 0{memset (G,0,sizeof(G));  for(intI=1; i<=m;i++) {scanf ("%d%d",&a,&b); G[A][B]=1; }           if(Toposort ()) { for(intI=0; i<n;i++)             if(!i) printf ("%d", Topo[i]); Elseprintf"%d", Topo[i]); printf ("\ n"); }             }    } 

"VJ Job" "Topological sorting classic comprehension problem" ordering Tasks 1, Kahn algorithm; 2, DFS-based algorithm.

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.