Ordering Tasks 拓扑排序

John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is
only possible if other tasks have already been executed.
Input
The input will consist of several instances of the problem. Each instance begins with a line containing
two integers, 1 n 100 and m. n is the number of tasks (numbered from 1 to n) and m is the
number of direct precedence relations between tasks. After this, there will be m lines with two integers
i and j, representing the fact that task i must be executed before task j.
An instance with n = m = 0 will finish the input.
Output
For each instance, print a line with n integers representing the tasks in a possible order of execution.
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3

拓扑排序:

代码1:

#include <iostream>
#include <cstdio>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
///拓扑排序学习题
int main()
{
int n,m,a,b,ans[];
while(scanf("%d%d",&n,&m))
{
if(!(n+m)^)break;
int mp[][]={},vis[]={},mark[]={};///mark用来记录是否有比自己优先的 如果有就
for(int i=;i<m;i++) /// 加1 可能有多个比自己优先的,如果没有比自己优先的 直接输出
{ ///mp记录是否有排在自己后面的 如果有就把mark减一 表示我已经输出了
scanf("%d%d",&a,&b); /// 对你没限制了 至于其他人对你有没有限制我不管了
mark[b]++; ///vis看是否被记录 ,记录了变为1
mp[a][b]=;
}
int j=,temp;
while(j<n)
{
temp=-;
for(int i=;i<=n;i++)
if(!vis[i]&&!mark[i])
{
ans[j++]=i;
temp=i;
break;
}
if(temp<)break;///不存在没记录的元素了 就停止
vis[temp]=; ///mark一下
for(int i=;i<=n;i++)
if(mp[temp][i]==)mark[i]--;
}
for(int i=;i<n;i++)
printf("%d ",ans[i]);
putchar('\n');
}
}

代码2:

#include <iostream>
#include <cstdio>
#include <queue>
#include <map>
#include <algorithm>
#include <cstring>
using namespace std;
///拓扑排序学习题 递归形式dfs 选中一个未排序的元素进行dfs把在他之后的装进ans(倒着装)并标记。 int n,m,a,b,ans[],mp[][]={},vis[]={},k;
bool dfs(int last)
{
vis[last]=-;
for(int i=;i<=n;i++)
if(mp[last][i])
{
if(vis[i]==)dfs(i);
else if(vis[i]==-)return false;//形成了回路 无法继续排序 -1表示i比last先入栈。
}
ans[--k]=last;
vis[last]=;
return true;
}
int main()
{
while(scanf("%d%d",&n,&m))
{
if(!(n+m))break;
k=n;
memset(vis,,sizeof(vis));
memset(mp,,sizeof(mp));
for(int i=;i<m;i++)
{
scanf("%d%d",&a,&b);
mp[a][b]=;
}
for(int i=;i<=n;i++)
{
if(!vis[i])
{
if(!dfs(i))break;
}
}
for(int i=k;i<n;i++)
printf("%d ",ans[i]);
putchar('\n');
}
}
上一篇:【Dev C++坦克大战】


下一篇:uva 10305 ordering tasks(超级烂题)——yhx