Topology Sort "template"

Source: Internet
Author: User
Tags in degrees

1. General judgment topology sequencing, output path: queue<int> Q
2. Topological ordering that satisfies the dictionary order: priority_queue<int,vector<int>, greater<int> > Q;
The priority of the weight is guaranteed to be high and the number is the smallest in the queue when it is taken out.
3. Satisfy the smallest possible in front (not guaranteed to be dictionary order): priority_queue<int> Q;
Reverse build, with priority queue storage will be 0 points, and then traverse the value of large nodes, from large to small deposit array ans[], and finally ans[] reverse order is to meet the requirements of the topological ordering

Const intMAXN = the;Const intMAXM =10010;intHead[maxn],indegree[maxn],ans[maxn],n,m,t;//indegree[] Storage in degrees, ans[] reverse order to store topological sequencesstructedgenode{intto;intWintNext;}; Edgenode EDGES[MAXM];intToposort () { Queue<int>Q;//topology sequencing    intU for(inti =1; I <= N; i++) {if(Indegree[i] = =0) Q.push (i); }intID =0; while(!        Q.empty ()) {u = Q.front (); ans[id++] = u;//Record topology sequenceQ.pop (); for(inti = Head[u]; I! =-1; i = edges[i].next) {indegree[edges[i].to]--;if(indegree[edges[i].to]==0) {Q.push (edges[i].to); }        }    }if(id = = N) { for(inti = N; I >=1; i--)//Reverse Output            if(I! =1)cout<< Ans[i] <<" ";Else                  cout<< Ans[i] << Endl;return true; }Else        return false;}

Topology Sort "template"

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.