首页 > 代码库 > Ordering Tasks 拓扑排序

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[100];    while(scanf("%d%d",&n,&m))    {        if(!(n+m)^0)break;        int mp[101][101]={0},vis[101]={0},mark[101]={0};///mark用来记录是否有比自己优先的 如果有就        for(int i=0;i<m;i++)            /// 加1 可能有多个比自己优先的,如果没有比自己优先的 直接输出        {                          ///mp记录是否有排在自己后面的 如果有就把mark减一 表示我已经输出了            scanf("%d%d",&a,&b);           /// 对你没限制了 至于其他人对你有没有限制我不管了            mark[b]++;                         ///vis看是否被记录 ,记录了变为1            mp[a][b]=1;        }        int j=0,temp;        while(j<n)        {            temp=-1;            for(int i=1;i<=n;i++)                if(!vis[i]&&!mark[i])                {                    ans[j++]=i;                    temp=i;                    break;                }            if(temp<0)break;///不存在没记录的元素了 就停止            vis[temp]=1; ///mark一下            for(int i=1;i<=n;i++)                if(mp[temp][i]==1)mark[i]--;        }        for(int i=0;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的最先记录int n,m,a,b,ans[101],mp[101][101]={0},vis[101]={0},k;bool dfs(int last){    vis[last]=-1;    for(int i=1;i<=n;i++)        if(mp[last][i])        {            if(vis[i]==0)dfs(i);            else if(vis[i]==-1)return false;//形成了回路 无法继续排序        }    ans[--k]=last;    vis[last]=1;    return true;}int main(){    while(scanf("%d%d",&n,&m))    {        if(!(n+m))break;        k=n;        memset(vis,0,sizeof(vis));        memset(mp,0,sizeof(mp));        for(int i=0;i<m;i++)        {            scanf("%d%d",&a,&b);            mp[a][b]=1;        }        for(int i=1;i<=n;i++)        {            if(!vis[i])            {                if(!dfs(i))break;            }        }        for(int i=k;i<n;i++)            printf("%d ",ans[i]);        putchar(\n);    }}

 

Ordering Tasks 拓扑排序