暑假训练 Ordering Tasks UVA - 10305 拓扑排序

描述:
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

代码:

#include<iostream>
#include<string.h>
#include<queue>
#define maxn 105
using namespace std;
int n,m,p1,p2,num=0;
bool rop[maxn][maxn];
int in[maxn];
int main()
{
    while(cin>>n>>m&&n!=0){
        if(m==0){
            for(int i=1;i<n;i++)
                cout<<i<<' ';
            cout<<n<<endl;
        continue;
        }
        queue <int>q;
        num=0;
        memset(rop,0,sizeof(rop));
        memset(in,0,sizeof(in));
        for(int i=0;i<m;i++){
            cin>>p1>>p2;
            if(rop[p1][p2]==0){
            rop[p1][p2]=1;
            in[p2]++;
            }
        }
        for(int i=1;i<=n;i++){
            if(in[i]==0){q.push(i);in[i]=maxn;}
        }
        while(!q.empty()){
            num++;
            if(num<n)cout<<q.front()<<' ';
            else {cout<<q.front()<<endl;break;}
            for(int i=1;i<=n;i++){
                if(rop[q.front()][i]){in[i]--;rop[q.front()][i]=0;}
            }
            q.pop();
            for(int i=1;i<=n;i++)
                if(in[i]==0){q.push(i);in[i]=maxn;}
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wbl1970353515/article/details/82822665