Topological sort templates

Source: Internet
Author: User

1 /*2 Toposort: Topological ordering3 in[]: the degree of entry of each point; ans[]: the result of sorting;4 Return:true: There is a ring; false: no ring5 */6 BOOLToposort (void)7 {8memset (inch,0,sizeof(inch));//in-degree emptying9      for(intI=1; i<=n; ++i)Ten          for(intj=0; J<g[i].size (); ++J)inch[g[i][j]]++;//all points with arrows pointing to the in-degree accumulation One  Aqueue<int> Q;intCNT =0; -      for(intI=1; i<=n; ++i) {if(!inch[i]) q.push (i);}//First look for the entry and exit read as 0 points, the queue in ascending order -  the      while(!q.empty ()) -     { -         intU =Q.front (); Q.pop (); -ANS[++CNT] = u;//ans[] Stores the point after the topology is sorted +          for(intj=0; J<g[u].size (); ++j) -         { +             intv =G[u][j]; A             inch[v]--;//Decrease one entry at a time at             if(!inch[v]) Q.push (v);//if 0, the first team, the topological sequence of the front -         } -     } -  -     if(cnt = = N)return false; -     Else return true;//if there are no n points, it indicates a ring, YES in}
Queue Implementation (annotated version)
1 BOOLToposort (void)2 {3memset (inch,0,sizeof(inch));4      for(intI=1; i<=n; ++i)5          for(intj=0; J<g[i].size (); ++J)inch[g[i][j]]++;6 7queue<int> Q;intCNT =0;8      for(intI=1; i<=n; ++i) {if(!inch[i]) q.push (i);}9 Ten      while(!q.empty ()) One     { A         intU =Q.front (); Q.pop (); -ANS[++CNT] =u; -          for(intj=0; J<g[u].size (); ++j) the         { -             intv =G[u][j]; -             inch[v]--; -             if(!inch[v]) Q.push (v); +         } -     } +  A     if(cnt = = N)return false; at     Else return true; -}
Queue Implementation (no comment version)

Topological sort templates

Related Article

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.