http://acm.hdu.edu.cn/showproblem.php?pid=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队。
拓扑排序模板题。刷dfs的时候遇到的。干脆来学习下。
注意可能有重边。
由于要求输出顺序按照序号从小到达,所以这里用了优先队列。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
/* *********************************************** Author :111qqz Created Time :2015年12月08日 星期二 20时43分24秒 File Name :code/hdu/1285.cpp ************************************************ */ #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #define fst first #define sec second #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define ms(a,x) memset(a,x,sizeof(a)) typedef long long LL; #define pi pair < int ,int > #define MP make_pair using namespace std; const double eps = 1E-8; const int dx4[4]={1,0,0,-1}; const int dy4[4]={0,-1,1,0}; const int inf = 0x3f3f3f3f; const int N=5E2+7; int n,m; int in[N]; bool con[N][N]; priority_queue<int,vector<int>,greater<int> > q; void toporder() { for ( int i = 1 ; i <= n ; i++) if (in[i]==0) q.push(i); int c = 1; while (!q.empty()) { int v =q.top(); q.pop(); if (c!=n) { printf("%d ",v); c++; } else printf("%d\n",v); for ( int i = 1 ; i <= n ; i++) { if (!con[v][i]) continue; in[i]--; if (!in[i]) q.push(i); } } } int main() { #ifndef ONLINE_JUDGE freopen("code/in.txt","r",stdin); #endif while (scanf("%d %d",&n,&m)!=EOF) { ms(con,false); for ( int i = 0 ; i < m ; i++) { int x,y; scanf("%d %d",&x,&y); if (con[x][y]) continue; con[x][y] = true; in[y]++; } toporder(); } #ifndef ONLINE_JUDGE fclose(stdin); #endif return 0; } |
说点什么
您将是第一位评论人!