例题:传送门
1.此题的首要条件
由这两个条件可知需要写一个多测输入,即利用while死循环,进行多次测试.
while(1){
if()break; // 读到N=0结束 即if(N==0)break;
}
2. 此题需要输入学生数据进行整体排序,此时要考虑到结构体的使用,运用结构体整体排序
定义结构体
struct code{
int num; // 学号为6位,输出时注意右对齐用0补齐
char name[9]; // 字符串长度最多为8位,考虑到'\0',多定义一位
int score; // 成绩
}s[N]; // 结构体数组,N为题目所给需要测试的数据0<=N<=100000,用宏定义定义
3.按情况进行排序,此时需要利用switch选择,利用sort排序,用cmp函数定义相应情况
switch(c){
case 1:
sort(s,s+n,cmp1);
break;
case 2:
sort(s,s+n,cmp2);
break;
case 3:
sort(s,s+n,cmp3);
break;
}
int cmp1(code a, code b) {
return a.num < b.num; // 小于从小到大 ,大于从大到小
}
int cmp2(code a, code b) {
if(a.name[0]!=b.name[0]){ // 如果首字符相同则按学号排
return a.name[0] < b.name[0];
}else{
return a.num < b.num;
}
}
int cmp3(code a, code b) {
if(a.score!=b.score){ // 如果成绩相同则按学号排
return a.score < b.score;
}else{
return a.num < b.num;
}
}
4.最后整理代码,完整代码如下
#include <iostream>
#include <algorithm>
#include <string.h>
#include <iomanip>
using namespace std;
#define N 100010
struct code{
int num;
char name[9];
int score;
}s[N];
int cmp1(code a, code b) {
return a.num < b.num;
}
int cmp2(code a, code b) {
if(a.name[0]!=b.name[0]){
return a.name[0] < b.name[0];
}else{
return a.num < b.num;
}
}
int cmp3(code a, code b) {
if(a.score!=b.score){
return a.score < b.score;
}else{
return a.num < b.num;
}
}
int main()
{
int i,n,c;
while(1){
cin>>n>>c;
for(i = 0; i < n; i++){
cin>>s[i].num>>s[i].name>>s[i].score;
}
switch(c){
case 1:
sort(s,s+n,cmp1);
break;
case 2:
sort(s,s+n,cmp2);
break;
case 3:
sort(s,s+n,cmp3);
break;
}
cout<<"Case"<<" "<<c<<"\n";
for(i = 0; i < n; i++){
cout<<setfill('0')<<setw(6)<<s[i].num<<" "<<s[i].name<<" "<<s[i].score<<"\n";
} // 利用setfill('0')补零,setw(6)右对齐空6位字符
if(n==0)break;
}
}
总结:1.看到多测数据时,要想到用while死循环
2.利用结构体进行多组数据的排序
3.利用sort函数进行快速排序,用cmp定义排序的类型