Topo Sort full version

Source: Internet
Author: User

Input data:

4 6
1 2
1 3
2 3
3 4
2 4
4 2

4 6
1 2
1 3
2 3
3 4
2 4
1 2

Topo sort to partial order:

Demo: http://www.tyut.edu.cn/kecheng1/site01/suanfayanshi/topological_sort.asp

Details: http://blog.csdn.net/dm_vincent/article/details/7714519

1#include <stdio.h>2#include <queue>3#include <string.h>4 using namespacestd;5 intindegree[ -] ;6queue<int>Q;7 intN, M;8 BOOLmap[ -][ -] ;9 inta[ -] ;Ten intTopointN) One { A     intCNT =0 ; -      while(!q.empty ()) - Q.pop (); the  -      for(inti =1; I <= N; i++) { -         if(Indegree[i] = =0) { -Q.push (i);//A point with an entry of 0 is the starting point +         } -     } +  A     inttemp; at      while(!Q.empty ()) { -temp =Q.front (); -A[cnt + +] =temp; - Q.pop (); -          for(inti =1; I <= N; i++) { -             if(Map[temp][i]) { inindegree[i]--; -                 if(Indegree[i] = =0) to Q.push (i); +             } -         } the     } *     if(cnt = = N)//output has loop information when the number of vertices in the output is less than the number of vertices in the graph $          for(inti =0; I < n; i++) {Panax Notoginsengprintf ("%d----->", A[i]); -     } the     Else +Puts ("The network has a cycle!") ; A } the  + intMain () - { $    //freopen ("A.txt", "R", stdin); $     intu, v; -      while(~ scanf ("%d%d", &n, &m)) { -memset (Indegree,0,sizeof(Indegree)); thememset (Map,0,sizeof(map)); -          for(inti =0; I < m; i++) {Wuyiscanf ("%d%d", &u, &v); the             if(!map[u][v])//when u and V are not connected -indegree[v]++;//entry of Point V + + WuMAP[U][V] =1;//indicates connectivity -         } About topo (n); $     } -}
View Code

Topo Sort full version

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.