拓扑排序水题,这题要求如果有两个点同时入度为0时,要求序号小的排前面,所以用邻接矩阵爆搜两遍就好了,应该是比用dfs好处理的。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int n,m;
int graph[105][105];
int indegree[105];
queue <int> q;
void toposort(){
for(int i=1;i<=n;i++){
for(int k=1;k<=n;k++){
if(!indegree[k]){ //从入度数为0的集合中删去一个点
indegree[k]--;
q.push(k);
for(int j=1;j<=n;j++){
if(graph[k][j]==1){
indegree[j]--;
}
}
for(int l=1;l<=n;l++){
printf("%d ",indegree[l]);
}printf("\n");
}
}
}
}
int main(){
while(scanf("%d %d",&n,&m)!=EOF&&(m||n)){
memset(graph,0,sizeof(graph));
memset(indegree,0,sizeof(indegree));
for(int i=1;i<=m;i++){
int a,b;
scanf("%d %d",&a,&b);
if(!graph[a][b]){
graph[a][b]=1;
indegree[b]++;
}
}
toposort();
int flag=1;
while(!q.empty()){
if(flag){
cout<<q.front();
q.pop();
flag=0;
}
else{
cout<<" "<<q.front();
q.pop();
}
}
cout<<endl;
}
return 0;
}