(hdu step 5.2.5)確定比賽名次(求拓撲序列),hdu5.2.5
題目:
| 確定比賽名次 |
| Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
| Total Submission(s): 337 Accepted Submission(s): 180 |
| |
| 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 31 22 34 3 |
Sample Output
1 2 4 3 |
| AuthorSmallBeer(CML) |
| Source杭電ACM集訓隊訓練賽(VII) |
| Recommendlcy |
題目分析:
拓撲序列,簡單題。
這裡面也還有幾道拓撲序列的題:http://blog.csdn.net/hjd_love_zzt/article/details/28700653
使用鄰接矩陣AC的代碼:
/* * e1.cpp * * Created on: 2015年3月8日 * Author: Administrator */#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 505;int map[maxn][maxn];//串連情況.例如map[a][b]=1表示a與b連通int indegree[maxn];//用於儲存各點的入度int queue[maxn];//最後的拓撲序列int n;//點數int m;//邊數int cnt;//拓撲序列中的節點數/** * 求拓撲序列 */void topo() {int i;int j;int k;for (i = 1; i <= n; ++i) {//枚舉所有起點for (j = 1; j <= n; ++j) {//枚舉所有終點if (indegree[j] == 0) {//如果某一終點的入度為0indegree[j]--;//移除該點queue[cnt++] = j;//將該點加入拓撲序列中//將以該點為起點的所有邊的終點的入度-1for (k = 1; k <= n; ++k) {if (map[j][k] != 0) {indegree[k]--;}}break;//這個一定要有,否則會wa。break只對本層迴圈起作用。不對if-esle語句起作用}//存在環的情況if (j > n) {cout << "存在環" << endl;return;}}}}int main() {while (scanf("%d%d", &n, &m) != EOF) {memset(indegree, 0, sizeof(indegree));memset(map, 0, sizeof(map));cnt = 0;int i;for (i = 0; i < m; ++i) {int a, b;scanf("%d%d", &a, &b);if (map[a][b] == 0) {//去重.這道題可能存在重複資料。例如1 2這組資料出現多次map[a][b] = 1;indegree[b]++;}}topo();for (i = 0; i < cnt - 1; ++i) {printf("%d ", queue[i]);}printf("%d\n", queue[cnt - 1]);}return 0;}
使用鏈式前向星實現的拓撲排序,不過輸出的順序不符合這道題的題意,但是大家可以藉此學一下
鏈式前向星的寫法:
/* * e.cpp * * Created on: 2015年3月8日 * Author: Administrator */#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 501;const int maxm = maxn * maxn;struct edge {int to;int weight;int next;} edge[maxm];int head[maxn];int indegree[maxn];int n, m;void topo() {int queue[maxn];int iq = 0;int i;for (i = 1; i <= n; ++i) {if (indegree[i] == 0) {queue[iq++] = i;}}for (i = 0; i < iq; ++i) {int k;for (k = head[queue[i]]; k != -1; k = edge[k].next) {indegree[edge[k].to]--;if (indegree[edge[k].to] == 0) {queue[iq++] = edge[k].to;}}}for(i = 0 ; i <= iq-2 ; ++i){printf("%d ",queue[i]);}printf("%d\n",queue[iq-1]);//if (iq < n) { //如果iq的最終值小於n.說明拓撲序列不存在...//printf("T_T\n");//printf("%d\n", n - iq);//} else {//printf("o(∩_∩)o\n");//}}int main() {while (scanf("%d%d", &n, &m) != EOF) {memset(head, -1, sizeof(head));memset(indegree, 0, sizeof(indegree));int cnt = 0;int i;for (i = 1; i <= m; ++i) {int a;int b;scanf("%d%d", &a, &b);indegree[b]++;edge[cnt].to = b;edge[cnt].next = head[a];head[a] = cnt++;}topo();}return 0;}