题意:给定一些任务,和任务序列 i j,意思是要求任务 i 必须要在任务 j 前完成。给出这样的任务序列。
思路:拓扑排序。
注意的是任务是从1开始的到n。
Code:
#include<stdio.h>
#include<string.h>
bool dfs(int u,int n);
bool toposort(int n);
int graph[105][105];
int topo[105];
int t;
int vis[105];
int main()
{
  int n,m;
  //while(scanf("%d%d",&n,&m)==2 && n && m)
  while(scanf("%d%d",&n,&m)==2 && (n||m))
  {
    t=n;        
    memset(vis,0,sizeof(vis));
    memset(graph,0,sizeof(graph));
    for(int i=0;i<m;++i)
    {
      int u,v;
      scanf("%d%d",&u,&v);
      graph[u][v]=1;
    }               
    if(toposort(n))
    {
      for(int i=0;i<n-1;++i) printf("%d ",topo[i]);
      printf("%d\n",topo[n-1]);
    }
  }
  return 0;  
}
bool toposort(int n)
{
  for(int u=1;u<=n;++u)
   if(!vis[u])
   {
     if(!dfs(u,n)) return false;
   }
  return true;
}
bool dfs(int u,int n)
{
  vis[u]=-1;
  for(int v=1;v<=n;++v)
   if(graph[u][v])
   {
     if(vis[v]==-1) return false;
     if(!vis[v] && !dfs(v,n)) return false;      
   }
  vis[u]=1;
  topo[--t]=u;
  return true;
}
原文:http://blog.csdn.net/buxizhizhou530/article/details/43493411