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的时候遇到的。干脆来学习下。
注意可能有重边。
由于要求输出顺序按照序号从小到达,所以这里用了优先队列。
/* ***********************************************
Author :111qqz
Created Time :2015年12月08日 星期二 20时43分24秒
File Name :code/hdu/1285.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=5E2+7;
7int n,m;
8int in[N];
9bool con[N][N];
10priority_queue<int,vector<int>,greater<int> > q;
11void toporder()
12{
13 for ( int i = 1 ; i <= n ; i++)
14 if (in[i]==0) q.push(i);
1 int c = 1;
2 while (!q.empty())
3 {
4 int v =q.top();
5 q.pop();
6 if (c!=n)
7 {
8 printf("%d ",v);
9 c++;
10 }
11 else
12 printf("%d\n",v);
13 for ( int i = 1 ; i <= n ; i++)
14 {
15 if (!con[v][i])
16 continue;
17 in[i]--;
18 if (!in[i])
19 q.push(i);
20 }
21 }
22}
23int main()
24{
25 #ifndef ONLINE_JUDGE
26 freopen("code/in.txt","r",stdin);
27 #endif
1 while (scanf("%d %d",&n,&m)!=EOF)
2 {
3 ms(con,false);
4 for ( int i = 0 ; i < m ; i++)
5 {
6 int x,y;
7 scanf("%d %d",&x,&y);
8 if (con[x][y])
9 continue;
10 con[x][y] = true;
11 in[y]++;
1 }
2 toporder();
3 }
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}