PAT A1028 List Sorting

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所指的列来排序:
| C | way |
|---|---|
| C=1 | 按ID ↑ |
| C=2 | 按name:non-decreasing |
| C=3 | 按grade:non-decreasing |
Ps.若grade 或 name 重 ,按ID排序↑
-
思路1:
简单的条件排序,因为排序的规则根据C而不同,所以在cmp中设一个switch函数,通过全局的c来选择sort的规则 -
code1:
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
using namespace std;
int n, c;
const int maxn = 110000;
struct Stu{
int id, grade;
string name;
}stu[maxn];
bool cmp(Stu a, Stu b){
switch(c){
case 1:
return a.id < b.id;
case 2:
if(a.name != b.name) return a.name < b.name;
else return a.id < b.id;
case 3:
if(a.grade != b.grade) return a.grade < b.grade;
else return a.id < b.id;
}
}
int main(){
scanf("%d %d", &n, &c);
for(int i = 0; i < n; ++i){
scanf("%d", &stu[i].id);
cin >> stu[i].name;
scanf("%d", &stu[i].grade);
}
sort(stu, stu+n, cmp);
for(int i = 0; i < n; ++i){
printf("%06d %s %d", stu[i].id, stu[i].name.c_str(), stu[i].grade);
if(i != n-1) printf("\n");
}
}
- T2 code:
#include <bits/stdc++.h>
using namespace std;
int c; //c == 1: id增; c == 2:name增; c == 3:grade增
const int maxn = 100010;
struct Stu{
string name;
int id, grade;
}stu[maxn];
bool cmp(Stu a, Stu b){
if(c == 1) return a.id < b.id;
if(c == 2) return a.name != b.name ? a.name < b.name : a.id < b.id;
if(c == 3) return a.grade != b.grade ? a.grade < b.grade : a.id < b.id;
}
int main(){
int n;
scanf("%d %d", &n, &c);
for(int i = 0; i < n; ++i){
scanf("%d", &stu[i].id);
cin >> stu[i].name;
scanf("%d", &stu[i].grade);
}
sort(stu, stu+n, cmp);
for(int i = 0; i < n; ++i){
printf("%06d %s %d\n", stu[i].id, stu[i].name.c_str(), stu[i].grade);
}
return 0;
}
- T4 code:
#include <bits/stdc++.h>
using namespace std;
int n, c;
struct stu
{
string info[4];
};
vector<stu> ans;
bool cmp(stu & a, stu & b)
{
return a.info[c] != b.info[c] ? a.info[c] < b.info[c] : a.info[1] < b.info[1];
}
int main()
{
scanf("%d %d", &n, &c);
for(int i = 0; i < n; ++i)
{
stu tmp;
for(int j = 1; j <= 3; ++j)
{
cin >> tmp.info[j];
}
ans.push_back(tmp);
}
sort(ans.begin(), ans.end(), cmp);
for(int i = 0; i < ans.size(); ++i)
{
for(int j = 1; j <= 3; ++j)
{
cout << ans[i].info[j];
if(j < 3) printf(" ");
else printf("\n");
}
}
return 0;
}
本文深入解析了PATA1028题目中的列表排序算法,该算法根据指定列(如ID、姓名或成绩)进行排序,特别处理了姓名或成绩相同时按ID排序的情况。提供了三种不同的实现代码,包括条件排序、字符串信息处理和向量存储,展示了灵活运用C++标准模板库STL进行高效排序的方法。
804

被折叠的 条评论
为什么被折叠?



