【HDU - 1285】确定比赛名次 (拓扑排序)
生活随笔
收集整理的這篇文章主要介紹了
【HDU - 1285】确定比赛名次 (拓扑排序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題干:
有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 3Sample Output
1 2 4 3解題報告:
? ? 拓撲排序模板。用鄰接矩陣存圖,會超時。
?
?AC代碼:
#include<bits/stdc++.h>using namespace std; const int MAX = 500 + 5 ; struct Node {int to;int w;int ne; } e[MAX]; int in[MAX],head[MAX],ans[MAX]; int cnt = 0,top = 0; priority_queue<int,vector<int > ,greater<int> > pq; void init() {cnt = 0;top = 0;memset(in,0,sizeof(in));memset(head,-1,sizeof(head));while(!pq.empty() ) pq.pop(); } void add(int u,int v,int w) {e[cnt].to = v;e[cnt].w = w;e[cnt].ne = head[u];head[u] = cnt;cnt++; } int main() {int n,m;int u,v;while(~scanf("%d%d",&n,&m) ) {init();while(m--) {scanf("%d%d",&u,&v);add(u,v,0);in[v]++;}//預處理一下pq for(int i = 1; i<=n; i++) {if(in[i] == 0 ) pq.push(i);}while(!pq.empty() ) {int cur = pq.top();//養成習慣,bfs中也是,取出元素后都先給一個變量cur存著以免以后忘了pop,并且新的都用new表示 pq.pop();ans[++top] = cur;for(int i = head[cur]; i!=-1; i=e[i].ne) {in[e[i].to]--;if(in[e[i].to] == 0) pq.push(e[i].to);} }if(top != n ) printf("不成環\n");else {for(int i = 1; i<=top; i++) {printf("%d%c",ans[i],i==top?'\n':' ');}}}return 0 ; }超時代碼:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; //struct Edge { // int to; // int w; // int ne; // //} e[5000]; int maze[505][505]; int in[505]; void init() {memset(in,0,sizeof(in));memset(maze,0,sizeof(maze) ) ; } int main() {int n,m,u,v;int flag = 0;while(~scanf("%d%d",&n,&m) ) {init();while(m--) {scanf("%d%d",&u,&v);maze[u][v] = 1;in[v]++;}int cnt = 0 ;while(1) {if(cnt == n) break;flag = 0 ;for(int i = 1; i<=n; i++) {if(in[i] == 0) {in[i]--;if(cnt == n-1) {printf("%d\n",i);cnt++;}for(int j = 1; j<=n; j++) {if(maze[i][j] == 1) {flag = 1;in[j]--;maze[i][j] = 0;cnt++;printf("%d%c",i,cnt==n?'\n':' ');break;}}if(flag == 1) {break;}}}}}return 0 ;}?
總結
以上是生活随笔為你收集整理的【HDU - 1285】确定比赛名次 (拓扑排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【HDU - 1301】Jungle R
- 下一篇: 我国去年的GDP增长2.3%,有一邻国却