优秀的算法https://blog.csdn.net/whutshiliu/article/details/83096237
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).
每个输入文件包含一个测试用例。对于每种情况,第一行包含两个整数N(≤ 1 0 5)和C,在哪里N是记录数和C是您应该对记录进行排序的列。然后N行跟随,每行包含一个学生的记录。学生的记录包括他或她的不同ID(6位数字),名称(不超过8个字符且没有空格的字符串)和等级(0到100之间的整数,包括0和100)。
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.
对于每个测试用例,输出排序结果 N行。也就是说,如果C = 1然后记录必须按照ID的递增顺序排序; 如果C = 2则记录必须按名称按非递减顺序排序; 而如果C = 3然后记录必须根据等级按非递减顺序排序。如果有几个学生具有相同的名称或成绩,则必须按照其ID递增顺序对其进行排序。
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
#include<vector>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int id,grade;
string name;
};
int n,c,i;
bool cmp(node a,node b)
{
if(c==1) return a.id<b.id;///id从小到大
else if(c==2) return a.name!=b.name?a.name<b.name:a.id<b.id;
///名字不同按名字从小到大,相同按id从小到大
else return a.grade!=b.grade?a.grade<b.grade:a.id<b.id;
///成绩不同按成绩从小到大,相同按id从小到大
}
int main()
{
cin>>n>>c;
vector<node>v(n);
for(i=0; i<n; i++)
cin>>v[i].id>>v[i].name>>v[i].grade;
sort(v.begin(),v.end(),cmp);
for(auto it : v)
printf("%06d %s %d\n",it.id,it.name.c_str(),it.grade);
///c_str()返回正确的字符串排序strcmp型
}
学习了一个不用strcmp就可以比较字符串的方法,就是c_str()最后返回的是正确的排序;
还有(auto it:v)增强数组,后面输出就得用it.....