#44975: cpp 超級簡單解


1121232@stu.wghs.tp.edu.tw (Ian911436)

學校 : 臺北市私立薇閣高級中學
編號 : 258883
來源 : [60.248.154.143]
最後登入時間 :
2025-05-14 15:36:23
n327. The Tower of Names -- 板橋高中教學題 | From: [60.248.154.139] | 發表日期 : 2024-12-30 14:40

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool compare(const string &a, const string &b) {
    // 先比較長度,如果長度相同,再按字母順序排序
    if (a.size() == b.size()) {
        return a < b;  // 字母順序排序
    }
    return a.size() < b.size();  // 按長度排序
}

int main() {
    int n;
    cin >> n;  // 讀取名字的數量
    cin.ignore();  // 忽略換行符號

    vector<string> names(n);
    for (int i = 0; i < n; ++i) {
        getline(cin, names[i]);  // 讀取每行名字
    }

    // 使用自定義的比較函數進行排序
    sort(names.begin(), names.end(), compare);

    // 輸出排序後的名字
    for (const auto &name : names) {
        cout << name << endl;
    }

    return 0;
}

 
ZeroJudge Forum