HDU 1285 肯定比賽名次

肯定比賽名次

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19100    Accepted Submission(s): 7610


php

Problem Description
有 N個比賽隊(1<=N<=500),編號依次爲1,2,3,。。。。,N進行比賽,比賽結束後,裁判委員會要將全部參賽隊伍從前日後依次排 名,但如今裁判委員會不能直接得到每一個隊的比賽成績,只知道每場比賽的結果,即P1贏P2,用P1,P2表示,排名時P1在P2以前。如今請你編程序肯定 排名。
 

 

Input
輸入有若干組,每組中的第一行爲二個數N(1<=N<=500),M;其中N表示隊伍的個數,M表示接着有M行的輸入數據。接下來的M行數據中,每行也有兩個整數P1,P2表示即P1隊贏了P2隊。
 

 

Output
給出一個符合要求的排名。輸出時隊伍號之間有空格,最後一名後面沒有空格。

其餘說明:符合條件的排名可能不是惟一的,此時要求輸出時編號小的隊伍在前;輸入數據保證是正確的,即輸入數據確保必定能有一個符合要求的排名。
 

 

Sample Input
4 3 1 2 2 3 4 3
 

 

Sample Output
1 2 4 3
 

 

Author
SmallBeer(CML)
 

 

Source
 

 

Recommend
lcy
 
 
圖的拓撲排序,題目要求輸出時編號小的隊伍在前,可以使用優先隊列。
 
 1 #include <cstdio>
 2 #include <vector>
 3 #include <functional>
 4 #include <queue>
 5 using namespace std;
 6 bool cmp(const int &x,const int &y)
 7 {
 8     return x>y;
 9 }
10 
11 const int maxn=550;
12 vector<int> v[maxn];
13 int indegree[maxn];
14 priority_queue<int,vector<int>,greater<int> >q;
15 queue<int> s;
16 int main()
17 {
18     int n,m,a,b;
19     while(scanf("%d%d",&n,&m)==2)
20     {
21         for(int i=1;i<=n;i++) indegree[i]=0;
22         for(int i=0;i<m;i++)
23         {
24             scanf("%d%d",&a,&b);
25             v[a].push_back(b);
26             indegree[b]++;
27         }
28         for(int i=1;i<=n;i++)
29             if(indegree[i]==0) q.push(i);
30         while(!q.empty())
31         {
32             int t=q.top(); q.pop();
33             for(int i=0;i<v[t].size();i++)
34             {
35                 indegree[v[t][i]]--;
36                 if(indegree[v[t][i]]==0) q.push(v[t][i]);
37             }
38             s.push(t);
39         }
40         int first=true;
41         while(!s.empty())
42         {
43             if(first){printf("%d",s.front()); first=false;}
44             else  printf(" %d",s.front());
45             s.pop();
46         }
47         printf("\n");
48         for(int i=1;i<=n;i++) v[i].clear();
49     }
50     
51 }
相關文章
相關標籤/搜索