UVA10305 ordering Tasks (topological sequence)

Source: Internet
Author: User

Test instructions

Suppose there are n variables, and a M two-tuple (U, v), which indicates that the variable u is less than V, respectively. So. What should all the variables look like from small to large? For example, there are four variables a,b,c,d, if a < B, C < b, D < C, then these four variables may be ordered a < D < C < b; Although there are other possibilities, you just need to find one.

Ideas:

Consider each variable as a point, and "less than" as an edge, and then get a forward graph. In this way, the actual task is to sort all the nodes of a graph, so that each corresponding to the forward edge (U, v), the corresponding u are in front of the V, that is, topological ordering.

Code:

#include <stdio.h>#include<string.h>#include<iostream>#include<math.h>#include<queue>#include<stack>#include<algorithm>using namespacestd; Const intMAXV = -;intHEAD[MAXV +7];intN, M;queue<int>ansqu;structedgenode{intto ; intNext;} EDGES[MAXV* MAXV +7];intINDEGREE[MAXV];voidGETIDG ()//Get into degrees {memset (Indegree,0,sizeof(Indegree));  for(inti =1; I <= m; i++) indegree[Edges[i].to]++;}voidTplgsort ()//topological sort {getidg (); Stack<int>Tpst;  for(inti =1; I <= N; i++)        if(!Indegree[i]) Tpst.push (i);  while(!Tpst.empty ()) {        intv =Tpst.top ();        Ansqu.push (v);        Tpst.pop ();  for(intj = Head[v]; J! =-1; j =edges[j].next)if(! (--indegree[edges[j].to]))    Tpst.push (edges[j].to); }}intMain () { while(~SCANF ("%d%d", &n, &m) && (n | |m) {memset (head,-1,sizeof(head)); memset (&edges,0,sizeof(Edgenode));  for(inti =1; I <= m; i++)        {            intu, v; scanf ("%d%d", &u, &v); Edges[i].to=v; Edges[i].next=Head[u]; Head[u]=i;        } tplgsort (); intFlag =0;  while(!Ansqu.empty ()) {printf (flag++ ?"%d":"%d", Ansqu.front ());        Ansqu.pop (); } printf ("\ n"); }    return 0;}

UVA10305 ordering Tasks (topological sequence)

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.