hdoj 1285 to determine the competition ranking

Determine the ranking of the competition

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 32757    Accepted Submission(s): 12834


Problem Description
There are N teams (1<=N<=500), numbered 1, 2, 3, in order. . . . , N to play the game. After the game, the referee committee will rank all participating teams from front to back, but now the referee committee cannot directly obtain the game results of each team, only know the result of each game, that is, P1 wins P2, using P1, P2 means that P1 is ahead of P2 when ranking. Now please program to determine the ranking.
 

Input
There are several groups of input, and the first row in each group is two numbers N (1<=N<=500), M; where N represents the number of teams, and M represents the input data followed by M rows. In the next M lines of data, each line also has two integers P1, and P2 means that the P1 team wins the P2 team.
 

Output
Give a ranking that meets the requirements. There are spaces between the team numbers when outputting, and there is no space after the last.

Other instructions: The ranking that meets the conditions may not be unique. In this case, the team with the smaller number is required to be first in the output; the input data is guaranteed to be correct, that is, the input data ensures that there must be a ranking that meets the requirements.
 

Sample Input
 
  
4 3 1 2 2 3 4 3
 

Sample Output
 
  
1 2 4 3
 

Author
SmallBeer(CML)

topology + queue

#include<stdio.h>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
int degree[510];//The in-degree of the storage node
int visit[510];//Whether the marked node is pushed into the stack
int main(){
	int N,M,p1,p2;
	vector<int>v[510];//Use vector to store the adjacency list
	queue<int>q;
	while(scanf("%d %d",&N,&M)!=EOF){
		memset(visit,0,sizeof(visit));
		memset(degree,0,sizeof(degree));
		while(!q.empty())
		q.pop();
		for(int i=1;i<=N;i++)
		v[i].clear();
		for(int i=0;i<M;i++){
			scanf("%d %d",&p1,&p2);
			v[p1].push_back(p2);
			degree[p2]++;
		}
		for(int i=1;i<=N;i++){
			if(degree[i]==0){
				visit[i]=1;
				q.push(i);
				break;
			}
		}
		int num=1;
		while(!q.empty()){
			if(num==N)
			printf("%d\n",q.front());
			else{
				printf("%d ",q.front());
				num++;
			}
			int t=q.front();
			q.pop();
			for(int i=0;i<v[t].size();i++){//将入度-1
				degree[v[t][i]]--;
			}
			for(int i=1;i<=N;i++){
				if(degree[i]==0&&visit[i]==0){
					visit[i]=1;
					q.push(i);
					break;
				}
			}
		}
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324838676&siteId=291194637
Recommended