1. 程式人生 > >Ordering Tasks 拓撲排序

Ordering Tasks 拓撲排序

div == i++ out pri relation algo -- char

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 拓撲排序