2025年2月20日 星期四

ZeroJudge 解題筆記:e973. 3. 滿意度調查 (Survey of Satisfaction)

作者:王一哲
日期:2025年2月20日



ZeroJudge 題目連結:e973. 3. 滿意度調查 (Survey of Satisfaction)

解題想法


這題用 map 和自訂排序用的比較式,寫起來會很方便。

Python 程式碼


使用時間約為 32 ms,記憶體約為 4 MB,通過測試。
from collections import Counter
from functools import cmp_to_key

def mycmp(a, b):
    if a[0] > b[0]: return -1  # 如果 a[0] 大於 b[0],a 往前放
    elif a[0] < b[0]: return 1  # 如果 a[0] nc 於 b[0],a 往後放
    else:  # 如果 a[0] 等於 b[0]
        if a[1] < b[1]: return -1  # 如果 a[0] 小於 b[0],a 往前放
        elif a[1] > b[1]: return 1  # 如果 a[0] 大於 b[0],a 往後放
        else: return 0

cnt = Counter(list(input().strip()))  # 讀取字串,去掉結尾的 \n,轉成 list,傳入計數器
output = sorted([(val, key) for key, val in cnt.items()], key=cmp_to_key(mycmp))  # 讀取 cnt 的資料並排序
for i in range(len(output)):  # 印出答案
    print(output[i][1], end='\n' if i == len(output)-1 else ' ')


C++ 程式碼


使用時間約為 2 ms,記憶體約為 360 kB,通過測試。
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <utility>
#include <algorithm>
typedef long long LL;
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string s; cin >> s;  // 讀取字串
    map<char, LL> cnt;  // 計數器
    for(char c : s) cnt[c]++;  // 依序由 s 讀取字元 c,更新 cnt
    vector<pair<LL, char>> output;  // 輸出資料用的陣列
    for(auto it=cnt.begin(); it!=cnt.end(); it++) {  // 依序由 cnt 讀取 key, value
        output.push_back(make_pair((*it).second, (*it).first));  // 放入 {cnt[i], i}
    }
    sort(output.begin(), output.end(), [] (pair<LL, char> a, pair<LL, char> b) {
        if (a.first == b.first) return a.second < b.second;
        else return a.first > b.first; } );
    for(LL i=0; i<(LL)output.size(); i++) {  // 印出答案
        cout << output[i].second << " \n"[i == (LL)output.size()-1];
    }
    return 0;
}


沒有留言:

張貼留言