杭电ACM1285----确定比赛名次『拓扑排序』
1 //裸拓扑排序,注意先输出比较小的数,使用优先队列即可 2 #include <cstdio> 3 #include <vector> 4 #include <cstring> 5 #include <queue> 6 #include <algorithm> 7 using namespace std; 8 const int maxn = 505; 9 vector<int> v[maxn]; 10 priority_queue<int> q; 11 int f[maxn]; 12 int main() 13 { 14 int n,m,x,y; 15 while(~scanf("%d%d",&n,&m)) 16 { 17 memset(f,0,sizeof f); 18 for(int i = 1; i <= n; ++i) 19 v[i].clear(); 20 while(m--) 21 { 22 scanf("%d%d",&x,&y); 23 v[x].push_back(y); 24 ++f[y]; 25 } 26 for(int i = 1; i <= n; ++i) 27 if(f[i] == 0) 28 q.push(-i);//默认大根堆 29 bool flag = true; 30 while(!q.empty()) 31 { 32 int t = -q.top(); q.pop(); 33 if(flag) { printf("%d",t); flag = false;} 34 else printf(" %d",t); 35 for(int i = 0; i < v[t].size(); ++i) 36 if(!(--f[v[t][i]])) q.push(-v[t][i]); 37 } 38 printf("\n"); 39 } 40 return 0; 41 }