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 <algorithm>
#include <queue>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;
const int MAXN = 110;
vector<int> edges[MAXN];
int n,m;
int tdegress[MAXN];
int ta,tb;
int main(){
while(scanf("%d %d",&n,&m) != EOF){
if(n == 0 && m == 0) break;
memset(tdegress,0,sizeof(tdegress)); //出入度设置、
memset(edges,0,sizeof(edges));
for(int j = 0; j < m;++j){
scanf("%d %d",&ta,&tb);
tdegress[tb]++; //入度+1
edges[ta].push_back(tb);
}
//输入结束后,进行判断,先把入度为0的点放入队列
queue<int> task_queue; //维护一个任务队列
vector<int> sqe_vec; //顺序队列
for(int k = 1; k <= n;++k){
if(tdegress[k] == 0){
task_queue.push(k);
sqe_vec.push_back(k);
}
}
while(!task_queue.empty()){
int ttask = task_queue.front();
task_queue.pop();
for(int v = 0; v < edges[ttask].size();++v){
tdegress[edges[ttask][v]]--;
if(tdegress[edges[ttask][v]] == 0){
sqe_vec.push_back(edges[ttask][v]);
task_queue.push(edges[ttask][v]);
}
}
}
for(int i = 0; i < sqe_vec.size();++i){
printf("%d", sqe_vec[i]);
if(i < sqe_vec.size()-1) printf(" ");
}
cout<<endl;
}
system("PAUSE");
return 0;
}