推荐几个博客:https://blog.csdn.net/dm_vincent/article/details/7714519 拓扑排序的原理及其实现

https://blog.csdn.net/u012860063/article/details/38017661 拓扑排序的几种写法

https://blog.csdn.net/shahdza/article/details/7779389 拓扑排序题集

 

1.基于DFS的拓扑排序:一般适用于数据较小并且需要判断有无环的情况

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn=150;
 6 int n,vis[maxn],topo[maxn],cnt;
 7 bool g[maxn][maxn],flag;
 8 
 9 void dfs(int u)
10 {
11     if ( vis[u]<0 ) { 
12         flag=false;
13         return;
14     }
15     if ( vis[u]>0 ) return;
16     else vis[u]=-1; //表示当前还在访问中 
17     for ( int v=1;flag&&v<=n;v++ ) {
18         if ( g[u][v] ) dfs(v);
19     }
20     topo[cnt--]=u; //保存下来 
21     vis[u]=1; //访问完成 
22 }
23 
24 void toposort()
25 {
26     int i,j,k;
27     flag=true;
28     memset(vis,0,sizeof(vis)); //vis为0表示初从未访问过,为1表示已经已经访问完成,为-1表示当前还在访问中 
29     cnt=n;
30     for ( int i=1;i<=n&&flag;i++ ) {
31         if ( vis[i]==0 ) dfs(i);
32     }
33 }
34 
35 int main()
36 {
37     int i,m,x,y;
38     while ( scanf("%d%d",&n,&m)!=EOF ) {
39         memset(g,false,sizeof(g));
40         while ( m-- ) {
41             scanf("%d%d",&x,&y);
42             g[x][y]=true; //g存储两个点的关系 
43         }
44         toposort();
45         for ( int i=1;i<n;i++ ) printf("%d",topo[i]);
46         printf("%d\n",topo[n]);
47     }
48     return 0;
49 }
基于DFS的toposort

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-25
  • 2021-12-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案