【PAT】1004. Ranking(20)

1004. Ranking of achievements (20)

Read in the names, student IDs, and grades of n students, and output the names and student IDs of the students with the highest and lowest grades, respectively.

Input format: Each test input contains 1 test case in the format

  Line 1: positive integer n
  Row 2: The first student's name, student number, grades
  Row 3: The name and student number of the second student
  ... ... ...
  Line n+1: The name and student number of the nth student
The name and student ID are both strings of no more than 10 characters, and the grade is an integer between 0 and 100. It is guaranteed that no two students have the same grade in a set of test cases.

 

Output format: output 2 lines for each test case, the first line is the name and student ID of the student with the highest grade, the second line is the name and student ID of the student with the lowest grade, and there is a space between the strings.

Input sample:
3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
Sample output:
Mike CS991301
Joe Math990112 

defines a structure to store students' personal information.
Program description:
  1. The header file #include<bits/stdc++.h> contains all the header files in C++ and can be used directly
  2. The sort() function in the Standard Template Library (STL) is used, sort(a,b ,cmp) contains three parameters, a is the first address of the sorting interval, b is the next address of the ending address of the sorting interval, and the sorting interval is [a, b), for a[0] to a in an array a[100] [99]
   For sorting, you can directly write it as sort(a, a+100, cmp). The third parameter cmp is the comparison function, which is used to control whether the sort() function is sorted in ascending or descending order
  . 3. Since the standard is used Template library function, need to add:
using namespace std;

  

The C++ code is as follows:

1 #include<bits/stdc++.h>
 2  using  namespace std;
 3  struct student{
 4      string name;
 5      string id;
 6      int grade;
 7 } info[ 101 ];
 8  
9  bool compare(student a,student b){
 10      return a.grade<b.grade;     // 11 in ascending order 
 // return a.grade>b.grade;   // 12 in descending order }
 13 int main() {
 14 int n,i;
 15     
            cin>>n;
16     for(i=0;i<n;i++)
17         cin>>info[i].name>>info[i].id>>info[i].grade;
18     sort(info,info+n,compare);
19     cout<<info[n-1].name<<' '<<info[n-1].id<<endl;
20     cout<<info[0].name<<' '<<info[0].id<<endl;
21     system("pause");
22     return 0;
23}

Note: PAT test will show "segmentation fault" when info[] array is defined as info[100]

Guess you like

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