UVA 10305 Ordering Tasks

题意:

  给出n和m,n代表总共有几个箱子。接下来m行,每行有a,b,表示b在a之后。输出一个合理的序列。

分析:

  简单的拓扑排序:

代码:

  

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define MAX 100
int c[MAX];
int topo[MAX],t;
int n,m;
int g[MAX][MAX];
bool dfs(int u)
{
//cout<<u<<endl;
c[u]=-1;
for(int v=0;v<n;v++)
{
if(g[u][v])
{
//cout<<1<<" "<<v<<endl;
if(c[v]<0)
return false;
else if(!c[v] && !dfs(v))
return false;
}
}
c[u]=1;
topo[--t]=u;
return true;
}
bool toposort()
{
t=n;
memset(c,0,sizeof(c));
for(int u=0;u<n;u++)
if(!c[u]&&!dfs(u))
return false;
return true;
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m),n)
{
memset(g,0,sizeof(g));
while(m--)
{
scanf("%d%d",&i,&j);
i--;
j--;
g[i][j]=1;
}
toposort();
for(i=0;i<n;i++)
{
if(i!=0)
printf(" ");
printf("%d",topo[i]+1);
}
printf(" ");
}
return 0;
}
原文地址:https://www.cnblogs.com/137033036-wjl/p/4890074.html