10305 - Ordering Tasks

来源:互联网 发布:数组方法和字符串方法 编辑:程序博客网 时间:2024/05/16 00:29

John has n tasksto do. Unfortunately, the tasks are not independent and the execution of onetask is only possible if other tasks have already been executed.

Input

The input willconsist of several instances of the problem. Each instance begins with a linecontaining two integers, 1 <= n <= 100 and mn isthe number of tasks (numbered from 1 to n)and m is the number of direct precedence relations betweentasks. After this, there will be m lines with twointegers i and j, representing the fact that task i mustbe executed before task j. An instance with n = m = 0 willfinish the input.

Output

For each instance,print a line with n integers representing the tasks in apossible order of execution.

Sample Input

5 4

1 2

2 3

1 3

1 5

0 0

Sample Output        

1 4 2 5 3

代码:

#include<iostream>

#include<cstring>

using namespacestd;

 

const intmaxn=1000;

int G[maxn][maxn];//若(u,v)则将G[u][v]变为1

int topo[maxn];//存储拓扑排序后的结果

int n,m;

int temp;

int c[maxn];

/*

标记某结点是否被访问:0表示未被访问;-1表示正在被访问;1表示访问完毕

*/

 

bool  toposort();

bool dfs(int u);

 

int main()

{

    while(cin>>n>>m&&n)

    {

        memset(G,0,sizeof(G));

        memset(topo,0,sizeof(topo));

        int a,b;

        for(int i=0; i<m; i++)

        {

            cin>>a>>b;

            a--;//从0—N-1存储

            b--;

            G[a][b]=1;

        }

        if(toposort())

        {

            for(int i=0; i<n-1; i++)

            {

               cout<<topo[i]+1<<" ";//还原+1

            }

           cout<<topo[n-1]+1<<endl;

        }

    }

    return 0;

}

 

bool toposort()

{

    temp=n;

    memset(c,0,sizeof(c));//每组数据都要清空

    for(int i=0; i<n; i++)

    {

        if(!c[i])//若该节点没被访问过

        {

            if(!dfs(i))//若该图存在有向环

            {

                return false;

            }

        }

    }

    return true;

}

 

bool dfs(int u)

{

    c[u]=-1;//正在被访问

    for(int v=0;v<n;v++)

    {

        if(G[u][v])//存在优先关系

        {

            if(c[v]==-1)//存在有向环

            {

                return false;

            }

            if(c[v]==0)

            {

                dfs(v);//深搜

            }

        }

    }

    c[u]=1;//访问完毕

    topo[--temp]=u;

    return true;

}

题意:

把每个变量看成一个点,“小于”看成有向边,则得到一个有向图;将该图的所有节点排序,使得每一条有向边(u,v)对应的u都排在v的前面。若存在有向环,则不存在拓扑排序。只有有向无环图可以进行拓扑排序。

0 0
原创粉丝点击