HDU1285(拓扑排序裸题

。。被多组测试坑了一波

 1 #include<iostream>
 2 #include<vector>
 3 #include<queue>
 4 using namespace std;
 5 typedef long long ll;
 6 const int N = 1e3;
 7 vector<int>edge[N];
 8 vector<int> ans;
 9 priority_queue<int, vector<int>, greater<int> >q;
10 int n,m,l,r,in[N];
11 int main(){
12     ios::sync_with_stdio(0);
13     while(cin>>n>>m){
14         
15     ans.clear();while(!q.empty())q.pop();
16     for(int i = 1;i <= n;++i){in[i] = 0;edge[i].clear();}
17     
18     for(int i = 1;i <= m;++i){
19         cin>>l>>r;
20         edge[l].push_back(r);in[r]++;
21     }
22     for(int i = 1;i <= n;++i)if(in[i]==0)q.push(i);
23     while(!q.empty()){
24         int p = q.top();q.pop();
25         ans.push_back(p);
26         for(int i = 0; i < edge[p].size();++i){
27             int y = edge[p][i];in[y]--;
28             if(!in[y])q.push(y); 
29         }
30     }
31     for(int i = 0;i < n;++i){
32         if(i!=n-1)cout<<ans[i]<<" ";
33         else cout<<ans[i]<<endl;
34     }
35     }
36     return 0;
37 }
原文地址:https://www.cnblogs.com/h404nofound/p/11918749.html