Processing math: 100%

熱門文章

2025年4月24日 星期四

ZeroJudge 解題筆記:k399. 取貨 (Pickup)

作者:王一哲
日期:2025年4月24日



ZeroJudge 題目連結:k399. 取貨 (Pickup)

解題想法


這題用排序工具及 Python 的 tuple 或是 C++ 的 pair 會比較好寫。

Python 程式碼


使用時間約為 19 ms,記憶體約為 3.3 MB,通過測試。
import sys

for line in sys.stdin:
    cnt = dict()  # 記錄每個人最後一次登記的編號
    for i, c in enumerate(line.strip()): cnt[c] = i
    order = sorted([(v, k) for k, v in cnt.items()])  # 依照編號排序
    ans = sorted([(k, i) for i, (_, k) in enumerate(order, start=1)])  # 依照人的代號排序
    print("".join([str(i) for _, i in ans]))  # 將每個人對應的序號接成字串印出


C++ 程式碼


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

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string s;  // 登記順序
    while(cin >> s) {
        map<char, int> cnt;  // 記錄每個人最後一次登記的編號
        for(int i=0; i<(int)s.size(); i++) cnt[s[i]] = i;
        vector<pair<int, char>> order;  // 放入 {登記的編號, 代號},依照編號排序
        for(auto it : cnt) order.push_back(make_pair(it.second, it.first));
        sort(order.begin(), order.end());
        vector<pair<char, int>> ans;  // 依照人的代號排序
        for(int i=0; i<(int)order.size(); i++) ans.push_back(make_pair(order[i].second, i+1));
        sort(ans.begin(), ans.end());
        for(auto it : ans) cout << it.second;
        cout << "\n";
    }
    return 0;
}


沒有留言:

張貼留言