hdoj 1285 确定比赛名次
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/* ***********************************************
2Author :111qqz
3Created Time :2015年12月08日 星期二 20时43分24秒
4File Name :code/hdu/1285.cpp
5************************************************ */
6
7#include <cstdio>
8#include <cstring>
9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=5E2+7;
34int n,m;
35int in[N];
36bool con[N][N];
37priority_queue<int,vector<int>,greater<int> > q;
38void toporder()
39{
40 for ( int i = 1 ; i <= n ; i++)
41 if (in[i]==0) q.push(i);
42
43 int c = 1;
44 while (!q.empty())
45 {
46 int v =q.top();
47 q.pop();
48 if (c!=n)
49 {
50 printf("%d ",v);
51 c++;
52 }
53 else
54 printf("%d\n",v);
55 for ( int i = 1 ; i <= n ; i++)
56 {
57 if (!con[v][i])
58 continue;
59 in[i]--;
60 if (!in[i])
61 q.push(i);
62 }
63 }
64}
65int main()
66{
67 #ifndef ONLINE_JUDGE
68 freopen("code/in.txt","r",stdin);
69 #endif
70
71 while (scanf("%d %d",&n,&m)!=EOF)
72 {
73 ms(con,false);
74 for ( int i = 0 ; i < m ; i++)
75 {
76 int x,y;
77 scanf("%d %d",&x,&y);
78 if (con[x][y])
79 continue;
80 con[x][y] = true;
81 in[y]++;
82
83 }
84 toporder();
85 }
86
87 #ifndef ONLINE_JUDGE
88 fclose(stdin);
89 #endif
90 return 0;
91}