C++: Problem C: Sorting online courses

foreword

Record thinking on a sorting problem

topic

describe

The online class is finally over.
Many students have also returned to school.
HZSjYJ decided to reward and promote the top five schools in the online class. They selected three courses of Chinese, Mathematics and English, and scored three courses in each school.
Of course, the reward ranking rules are as follows:
1. The one with the higher total score of the three subjects
will be ranked first.
2. If the total score is the same, the one with the higher Chinese will be ranked at the top. Predetermined, is the input order)

enter

Enter an integer n in the first line, indicating the number of schools
, and then n lines, with 3 numbers in each line, representing the Chinese, Mathematics, and English scores of a school

output

Output 5 lines, which are the top 5 schools (output according to the ranking), each line has 2 integers, which are the serial number and the total score

sample

enter

6
90 67 80
87 66 91
78 89 91
88 99 77
67 89 64
78 89 98

output

6 265
4 264
3 258
2 244
1 237

analyze

Of course, this question can be done based on sorting, write a quick sort, and then change the sorting logic in it, but in this way, the entire input array must be stored and sorted, because there is only one sorting result of the top few, so May wish to use another way of thinking to solve this kind of problem

Only store the top few names, and only compare with the top few names each time

#include <iostream>
using namespace std;
int main(){
    
    
	int n;
	int tl[6]={
    
    0},ch[6]={
    
    0},ID[6]={
    
    0};
	//freopen("in.in","r",stdin);
	//freopen("out.out","w",stdout)  ;                                                                                                            
	cin>>n;	
	for(int i=0;i<n;i++){
    
    
		int totals,x,y,z;
		cin>>x>>y>>z;
		tl[5]=x+y+z; ch[5]=x;	ID[5]=i+1;
		for(int j=4;j>=0;j--){
    
    
			if(tl[j]<=tl[j+1]){
    
    
				if(tl[j+1]>tl[j] ||(tl[j]==tl[j+1] && ch[j+1]>ch[j] ))
				{
    
    
					int temp;
					temp=tl[j];tl[j]=tl[j+1];tl[j+1]=temp;
					temp=ch[j];ch[j]=ch[j+1];ch[j+1]=temp;
					temp=ID[j];ID[j]=ID[j+1];ID[j+1]=temp;					
				}
			}
			else break;
		}				
	}	
	
	for(int i=0;i<5;i++)
		cout<<ID[i]<<" "<<tl[i]<<endl;	
	
	return 0;	
}

Time complexity: O(n)
Space complexity: O(1)

Guess you like

Origin blog.csdn.net/qjyws/article/details/128318638