纯种的拓扑排序,参考刘汝佳《入门经典》上的代码稍加修改,完全可以AC ~
代码如下:
纯种的拓扑排序,参考刘汝佳《入门经典》上的代码稍加修改,完全可以AC ~
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define max 100+5
int c[max],topo[max],t,n,G[max][max];
int dfs(int u)
{
int v;
c[u] = -1;
for(v = 1; v <= n; v++)
if(G[u][v])
{
if(c[v] < 0) return 0;
else if(!c[v] && !dfs(v)) return 0;
}
c[u] = 1;
topo[--t] = u;
return 1;
}
int toposort()
{
int i;
t = n;
memset(c,0,sizeof(c));
for(i = 1; i <= n; i++)
if(!c[i] && !dfs(i))
return 0;
return 1;
}
int main()
{
#ifdef state
freopen("sample.txt","r",stdin);
#endif
int m,i;
while(scanf("%d%d",&n,&m),n || m)
{
int u,v;
memset(G,0,sizeof(G));
for(i = 0 ; i < m ; i++)
{
scanf("%d%d",&u,&v);
G[u][v] = 1;
}
if(toposort())
{
for(i = 0; i < n-1; i++)
printf("%d ",topo[i]);
printf("%d\n",topo[i]);
}
}
return 0;
}

本文介绍了一种基于刘汝佳《入门经典》中的纯种拓扑排序算法,并提供了完整的C语言实现代码。该算法通过深度优先搜索进行节点排序,适用于解决依赖关系问题。
1563

被折叠的 条评论
为什么被折叠?



