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
题意:按顺序输出入度为0的点。
这道题有点难以理解,小白的我看了好久,才总算明白题主要让我们做什么了。
分析:就是按照入度为0的顺序由小到大输出点,乍一看题中根本就没有给出4号点,那么4号点是从哪来的呢?其实在这种情况下就默认4号点的入度为0,所以就可以利用队列来解题了,用一个队列来存储入度为0的点,按照由小到大的顺序,那么也就可以把所有的点依次压入队列中了。
在此分享一下今天刚学到的小知识点,在for语句中用于判断的条件中含有 || 时表示只要两侧有一个条件为真时就可以进入循环语句,同时为家时方可退出循环,而 && 则不然它就表示只要两侧的条件有一个为假时那就必须退出循环!!!
代码如下:
#include<cstdio>
#include<vector>
#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#define ll long long
using namespace std;
const int MAXN=110;
int a,b,c,d,sum,s,point[MAXN];
queue <int > q;//记录节点入度为零的点
vector<int >ve[MAXN];//邻接矩阵
void fab(){
while(!q.empty()) q.pop();
for(int i=1;i<=a;i++){
if(point[i]==0){
q.push(i);
}
}
sum=0;
while(sum<a){
s=q.front();
q.pop();
sum++;
if(sum==1){
printf("%d",s);
}
else{
printf(" %d",s);
}
for(int i=0;i<ve[s].size();i++){
point[ve[s][i]]--;
if(point[ve[s][i]]==0){
q.push(ve[s][i]);
}
}
}
}
int main(){
while(scanf("%d%d",&a,&b)!=EOF&&(a||b)){
for(int i=0;i<a;i++){
ve[i].clear();
point[i]=0;
}
for(int i=0;i<b;i++){
scanf("%d%d",&c,&d);
point[d]++;
ve[c].push_back(d);
}
fab();
printf("\n");
}
return 0;
}