1028 List Sorting
1028 List Sorting (25分)
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:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
Sample Output 1:
000001 Zoe 60
000007 James 85
000010 Amy 90
Sample Input 2:
4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98
Sample Output 2:
000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60
Sample Input 3:
4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90
Sample Output 3:
000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90
审题
本题按要求将结构体数组排序:
-
c==1,将数组按“id”字段递增排序
-
c==2,将数组按"name"字段非递减排序
-
c==3,将数组按“grade”按非递减排序
输出排序后的结果。
思路
排序题可用sort函数解决。不过要注意cmp函数的实现要注意:
sort函数的cmp必须按照规定来写,即必须只是 > 或者 <
比如: return a > b; return a < b;
而不能是 <= 或者 >= ,(实际上等于号加了也是毫无意义,sort是不稳定的排序),否则可能会出现段错误
坑点
本题输入输出用cin和cout会超时,改用scanf和printf可通过。使用printf和scanf的时候要注意不能直接输入输出string类型,要先分配空间。这里为了方便我直接用了字符数组,没有使用string。
参考代码
1 #include<iostream> 2 #include<cstdio> 3 #include<string.h> 4 #include<algorithm> 5 using namespace std; 6 7 typedef struct{ 8 char id[7]; 9 char name[10]; 10 int grade; 11 }stu; 12 13 bool cmp1(stu a,stu b){ 14 return strcmp(a.id,b.id)<0; 15 } 16 17 bool cmp2(stu a,stu b){ 18 if(strcmp(a.name,b.name)!=0){ 19 return strcmp(a.name,b.name)<0; 20 } else { 21 return a.id<b.id; 22 } 23 } 24 25 bool cmp3(stu a,stu b){ 26 if(a.grade!=b.grade){ 27 return a.grade<b.grade; 28 } else { 29 return a.id<b.id; 30 } 31 } 32 33 stu s[100001]; 34 35 int main() 36 { 37 int n,c; 38 cin>>n>>c; 39 for(int i=0;i<n;i++){ 40 scanf("%s %s %d",&s[i].id,&s[i].name,&s[i].grade); 41 } 42 switch(c){ 43 case 1: 44 sort(s,s+n,cmp1); 45 break; 46 case 2: 47 sort(s,s+n,cmp2); 48 break; 49 case 3: 50 sort(s,s+n,cmp3); 51 break; 52 } 53 for(int i=0;i<n;i++){ 54 printf("%s %s %d\n",s[i].id,s[i].name,s[i].grade); 55 } 56 }

浙公网安备 33010602011771号