1028 List Sorting

爱被打了一巴掌 2024-04-08 11:10 190阅读 0赞

1028 List Sorting

0、题目

Excel can sort records according to any column. Now you are supposed to imitate this function.

Input Specification:

Each input file contains one test case. For each case, the first line contains two integers N (≤105) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, each contains a record of a student. A student’s record consists of his or her distinct ID (a 6-digit number), name (a string with no more than 8 characters without space), and grade (an integer between 0 and 100, inclusive).

Output Specification:

For each test case, output the sorting result in N lines. That is, if C = 1 then the records must be sorted in increasing order according to ID’s; if C = 2 then the records must be sorted in non-decreasing order according to names; and if C = 3 then the records must be sorted in non-decreasing order according to grades. If there are several students who have the same name or grade, they must be sorted according to their ID’s in increasing order.

Sample Input 1:

  1. 3 1
  2. 000007 James 85
  3. 000010 Amy 90
  4. 000001 Zoe 60

Sample Output 1:

  1. 000001 Zoe 60
  2. 000007 James 85
  3. 000010 Amy 90

Sample Input 2:

  1. 4 2
  2. 000007 James 85
  3. 000010 Amy 90
  4. 000001 Zoe 60
  5. 000002 James 98

Sample Output 2:

  1. 000010 Amy 90
  2. 000002 James 98
  3. 000007 James 85
  4. 000001 Zoe 60

Sample Input 3:

  1. 4 3
  2. 000007 James 85
  3. 000010 Amy 90
  4. 000001 Zoe 60
  5. 000002 James 9

Sample Output 3:

  1. 000002 James 9
  2. 000001 Zoe 60
  3. 000007 James 85
  4. 000010 Amy 90

1、大致题意

给表格排序,根据c的值是1还是2还是3,对相应的列排序。第一列升序,第二列不降序,第三列不降序

2、基本思路

sort大法,简单题

3、解题过程

3.1 char数组比较

注意,按照名称的不降序排序,因为 strcmp 比较的是 ACSII码 ,所以 A < Z 。写cmp函数 的时候 return strcmp(a.name, b.name) <= 0; return语句返回的是true或者false的值,所以要写 <= 0 这样的形式。比较 ACSII码 的大小,strcmp('a', 'z') 返回负值,因为 a<z a – z < 0
按照分数的不降序排序,a.score <= b.score

3.2 AC代码

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <string.h>
  4. using namespace std;
  5. const int maxn = 100001;
  6. struct NODE {
  7. int no, score;
  8. char name[10];
  9. }node[maxn];
  10. int c;
  11. int cmp1(NODE a, NODE b) {
  12. if(c == 1) {
  13. return a.no < b.no;
  14. } else if(c == 2) {
  15. if(strcmp(a.name, b.name) == 0) return a.no < b.no;
  16. return strcmp(a.name, b.name) <= 0;
  17. } else {
  18. if(a.score == b.score) return a.no < b.no;
  19. return a.score <= b.score;
  20. }
  21. }
  22. int main() {
  23. int n;
  24. scanf("%d%d", &n, &c);
  25. for(int i = 0; i < n; i++)
  26. scanf("%d %s %d", &node[i].no, node[i].name, &node[i].score);
  27. sort(node, node + n, cmp1);
  28. for(int i = 0; i < n; i++)
  29. printf("%06d %s %d\n", node[i].no, node[i].name, node[i].score);
  30. return 0;
  31. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,190人围观)

还没有评论,来说两句吧...

相关阅读