天天看點

1028 List Sorting (25 分| 排序,附詳細注釋,邏輯分析)

寫在前面

  • 實作思路
  • 結構體數組封裝學生中繼資料資訊
  • 自定義比較排序函數
  • 測試點
  • 題目較為基礎,熟練情況下15分鐘a題
  • ​字元串比較​

    ​​可能耗費時間,待驗證​

    ​==、<=​

    ​等比較符号問題
  • ​strcmp​

    ​無風險

測試用例

input:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
output:
000001 Zoe 60
000007 James 85
000010 Amy 90

input:
4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98
output:
000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60

input:
4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90
output:
000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90      

ac代碼

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int maxn = 100010;
struct Student
{
    int id;
    char name[10];
    int score;
} stu[maxn];

bool cmpbyid(Student a, Student b)
{
    return a.id < b.id;
}
bool cmpbyname(Student a, Student b)
{
    int cmp = strcmp(a.name, b.name);
    if(cmp==0)
        return a.id<b.id;
    return cmp<0;
}
bool cmpbyscore(Student a, Student b)
{
    if(a.score == b.score) return a.id<b.id;
    return a.score < b.score;
}
int main()
{
    int n, c;
    scanf("%d%d", &n, &c);
    for(int i=0; i<n; i++)
    {
        scanf("%d %s %d", &stu[i].id, stu[i].name, &stu[i].score);
    }
    if(c==1) sort(stu, stu+n, cmpbyid);
    else if(c==2) sort(stu, stu+n, cmpbyname);
    else sort(stu, stu+n, cmpbyscore);

    for(int i=0; i<n; i++)
    {
        printf("%06d %s %d\n", stu[i].id, stu[i].name, stu[i].score);
    }
}      

學習代碼

  • ​推薦​

    ​,常量技巧使用節省代碼量
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn = 100001;
struct NODE {
    int no, score;
    char name[10];
}node[maxn];
int c;
int cmp1(NODE a, NODE b) {
    if(c == 1) {
        return a.no < b.no;
    } else if(c == 2) {
        if(strcmp(a.name, b.name) == 0) return a.no < b.no;
        return strcmp(a.name, b.name) < 0;
    } else {
        if(a.score == b.score) return a.no < b.no;
        return a.score < b.score;
    }
}
int main() {
    int n;
    scanf("%d%d", &n, &c);
    for(int i = 0; i < n; i++)
        scanf("%d %s %d", &node[i].no, node[i].name, &node[i].score);
    sort(node, node + n, cmp1);
    for(int i = 0; i < n; i++)
        printf("%06d %s %d\n", node[i].no, node[i].name, node[i].score);
    return 0;
}