uva 10305 Ordering Tasks (拓扑排序)
这题用到的时最简单的拓扑排序,先建立大小关系的邻接矩阵,再拓扑排序
#include <iostream>
#include <queue>
#include <vector>
#include <cstdio>
using namespace std;
const int maxn=110;
bool a[maxn][maxn];
int degree[maxn],n,m;
void initial(){
for(int i=0;i<=n;i++){
degree[i]=0;
for(int j=0;j<=n;j++){
a[i][j]=false;
}
}
}
void input(){
int u,v;
while(m-- >0){
scanf("%d%d",&u,&v);
degree[v]++;
a[u][v]=true;
}
}
void solve(){
int s;
vector <int> v;
queue <int> q;
for(int i=1;i<=n;i++){
if(degree[i]==0){
q.push(i);
}
}
while(!q.empty()){
s=q.front();
q.pop();
v.push_back(s);
for(int i=1;i<=n;i++){
if(a[s][i]){
degree[i]--;
if(degree[i]==0){
q.push(i);
}
}
}
}
if(v.size()>0) printf("%d",v[0]);
for(int i=1;i<v.size();i++){
printf(" %d",v[i]);
}
cout<<endl;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF && (n||m)){
initial();
input();
solve();
}
return 0;
}