程序设计入门16 排序和排名与结构体

1025 PAT Ranking (25)(25 分)

Programming Ability Test (PAT) is organized by the College of ComputerScience and Technology of Zhejiang University. Each test is supposed torun simultaneously in several places, and the ranklists will be mergedimmediately after the test. Now it is your job to write a program tocorrectly merge all the ranklists and generate the final rank.

Input Specification:

Each input file contains one test case. For each case, the first linecontains a positive number N (<=100), the number of test locations.Then N ranklists follow, each starts with a line containing a positiveinteger K (<=300), the number of testees, and then K lines containingthe registration number (a 13-digit number) and the total score of eachtestee. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first print in one line the total number of testees.Then print the final ranklist in the following format:

registration_number final_rank location_number local_rank

The locations are numbered from 1 to N. The output must be sorted innondecreasing order of the final ranks. The testees with the same scoremust have the same rank, and the output must be sorted in nondecreasingorder of their registration numbers.

Sample Input:

2
5
1234567890001 95
1234567890005 100
1234567890003 95
1234567890002 77
1234567890004 85
4
1234567890013 65
1234567890011 25
1234567890014 100
1234567890012 85

Sample Output:

9
1234567890005 1 1 1
1234567890014 1 2 1
1234567890001 3 1 2
1234567890003 3 1 2
1234567890004 5 1 4
1234567890012 5 2 2
1234567890002 7 1 5
1234567890013 8 2 3
1234567890011 9 2 4

正确答案(心累!!!):

1,sort传的是指针。

2,那些下标之间的关系搞清楚。

3,能用for语句里面的变量表示,尽量用它,开很多新的变量会很乱。

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
struct Student{
	char id[15];
	int location;
	int local_rank;
	int score;
}stu[30010];
bool cmp(Student a,Student b){
	if(a.score!=b.score) return a.score>b.score;
	else return strcmp(a.id,b.id)<0;
}
int main(){
	int n,m,num=0;
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&m);
		for(int j=0;j<m;j++){
			scanf("%s %d",&stu[num].id,&stu[num].score);
			stu[num].location=i;
			num++;
		}
		
		sort(stu+num-m,stu+num,cmp);                     //注意sort用的是指针,而不是str[i] 
		stu[num-m].local_rank=1;
		for(int i=num-m+1;i<num;i++){
			if(stu[i].score==stu[i-1].score)
				stu[i].local_rank=stu[i-1].local_rank;
			else
				stu[i].local_rank=i-(num-m)+1;           //注意这里的i-(num-m)+1 
		}
	}
	
	
/*	for(int i=0;i<num;i++){
		printf("%d %d %d\n",stu[i].id,stu[i].location,stu[i].local_rank);
	}*/
	printf("%d\n",num);
	sort(stu,stu+num,cmp);
	int r=1;
	for(int i=0;i<num;i++){
		if(i>0&&stu[i].score!=stu[i-1].score){
			r = i + 1;
		}
		printf("%s %d %d %d\n",stu[i].id,r,stu[i].location,stu[i].local_rank);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq2285580599/article/details/80943934
今日推荐