Determine ranking in the game (HDU 1285)

Topic Link

Title Description

There are N match teams (1 <= N <= 500), followed by numbers 2, 3 ,. . . . , N the game, after the game, the referee committee want all the teams ranked in order from front to back, but referees are not directly available to each team's race results, only know the results of every game, that win P1 P2, with P1, P2, said when ranking P1 before P2. Now we're programmed to determine the rankings.

Input Format

Is input several groups, each group of two first line number N (1 <= N <= 500), M; where N is the number of teams, then M denotes the input data of M rows. The next M-line data, each line has two integers P1, P2 represents i.e. P1 P2 team won the team.

Output Format

Given a ranking in line with the requirements. There are spaces between the team No. output, there is no space after the last one.
Other notes: Eligible ranking may not be unique, which requires that when a small number of output ranks first; the input data is guaranteed to be correct, that is, the input data must be able to ensure that there is a satisfactory ranking.

SAMPLE INPUT

4 3
1 2
2 3
4 3

Sample Output

1 2 4 3

analysis

Subject to the effect of a given n points, directed graph, the minimum output topology sequence, a subject sequence to ensure that there is at least m edges.
Straight template to determine, pay attention to handling the heavy side.

Source

#include <bits/stdc++.h>
#define MAXN 505
using namespace std;
int n,m,in[MAXN],ans[MAXN];
bool g[MAXN][MAXN];
void TopSort()
{
	priority_queue<int,vector<int>,greater<int> > q;
	for(int i=1;i<=n;i++)
		if(!in[i])q.push(i);
	int cnt=0;
	while(!q.empty()){
		int u=q.top();
		q.pop();
		ans[++cnt]=u;
		for(int i=1;i<=n;i++)
			if(g[u][i]){
				in[i]--;
				if(!in[i])q.push(i);
			}
	}
}
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF&&n){
		memset(g,false,sizeof(g));
		memset(in,0,sizeof(in));
		for(int i=1;i<=m;i++){
			int u,v;
			scanf("%d%d",&u,&v);
			if(g[u][v])continue;	//重边 
			g[u][v]=true;
			in[v]++;
		}
		TopSort();
		for(int i=1;i<n;i++)
			printf("%d ",ans[i]);
		printf("%d\n",ans[n]);
	}
	return 0;
}
Published 19 original articles · won praise 0 · Views 129

Guess you like

Origin blog.csdn.net/weixin_43960284/article/details/105249579