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