标签:
Excel can sort records according to any column. Now you are supposed to imitate this function.
Input
Each input file contains one test case. For each case, the first line contains two integers N (<=100000) 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
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 13 1 000007 James 85 000010 Amy 90 000001 Zoe 60Sample Output 1
000001 Zoe 60 000007 James 85 000010 Amy 90Sample Input 2
4 2 000007 James 85 000010 Amy 90 000001 Zoe 60 000002 James 98Sample Output 2
000010 Amy 90 000002 James 98 000007 James 85 000001 Zoe 60Sample Input 3
4 3 000007 James 85 000010 Amy 90 000001 Zoe 60 000002 James 90Sample Output 3
000001 Zoe 60 000007 James 85 000002 James 90 000010 Amy 90
刚刚开始使用C++写,采用了string和vector,并且使用cin和cout进行输入输出,发现最后一个测试点运行超时。
最初以为是题目中有个点为以分数排序,因为分数排序可以采用桶排序(Buck-sort),然后改进了对于按分数排序的算法,结果发现最后一个点还是超时。
后面发现是因为题目中采用了cin和cout会占用大量的时间,将原来的string改成了用char,并且用scanf和printf进行输入输出,最后一个点能过通过。
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 5 using namespace std; 6 7 class Student 8 { 9 private: 10 char id[7]; 11 char name[9]; 12 int grade; 13 public: 14 friend bool cmp(const Student& s1, const Student& s2); 15 void read(){ scanf("%s%s%d", id, name, &grade); } 16 void output(){ printf("%s %s %d", id, name, grade); } 17 int GetGrade(){ return grade; } 18 }; 19 20 int column; 21 Student students[100001]; 22 23 bool cmp(const Student& s1, const Student& s2) 24 { 25 if (column == 1) 26 return strcmp(s1.id, s2.id) < 0; 27 else if (column == 2) 28 { 29 if (strcmp(s1.name, s2.name)) 30 return strcmp(s1.name, s2.name) < 0; 31 else 32 return strcmp(s1.id, s2.id) < 0; 33 } 34 else 35 { 36 if (s1.grade != s2.grade) 37 return s1.grade < s2.grade; 38 else 39 return strcmp(s1.id, s2.id) < 0; 40 } 41 } 42 43 int main() 44 { 45 int recordNum; 46 scanf("%d%d", &recordNum, &column); 47 48 for (int i = 0; i < recordNum; i++) 49 { 50 Student stu; 51 stu.read(); 52 students[i] = stu; 53 } 54 55 sort(students, students + recordNum, cmp); 56 for (int i = 0; i < recordNum; i++) 57 { 58 students[i].output(); 59 if (i < recordNum - 1) 60 printf("\n"); 61 } 62 }
标签:
原文地址:http://www.cnblogs.com/jackwang822/p/4711945.html