标签:
一个很裸的拓扑排序题目,只是因为很久没有复习toposort,所以拿来复习一下,最近几天要把图论的经典算法都复习一遍。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn=105;
bool G[maxn][maxn];
int n,m,t,c[maxn],topo[maxn];
bool dfs(int u)
{
c[u]=-1;
for(int v=1;v<=n;v++)
{
if(G[u][v])
{
if(c[v]<0)
return false;
else
{
if(!c[v]&&!dfs(v))
return false;
}
}
}
c[u]=1;
topo[t--]=u;
return true;
}
void toposort()
{
t=n;
memset(c,0,sizeof(c));
for(int u=1;u<=n;u++)
{
if(!c[u])
{
if(!dfs(u))
return;
}
}
}
int main()
{
while(scanf("%d%d",&n,&m))
{
memset(G,false,sizeof(G));
if(n==0&&m==0)
break;
int u,v;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
G[u][v]=true;
}
toposort();
for(int i=1;i<=n-1;i++)
printf("%d ",topo[i]);
printf("%d\n",topo[n]);
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/northsnow95/p/5544442.html