日期:2026年11月20日
ZeroJudge 題目連結:e666.108 p4. 排序問題
解題想法
這題的字母數量 $N$ 最大可達 $10^7$,如果真的用內建的工具將整個字串排序會超時,要改用桶子排序。開一個長度為 $26$ 的陣列 $cnt$,計算 A 到 Z 每個字母各有幾個,計算完畢之後再將 $cnt$ 轉成前綴和。如果要查詢排序後的第 $pos$ 個字母,可以用 Python 的 bisect_left 或是 C++ 的 lower_bound,從 $cnt$ 之中搜尋第一個大於、等於 $pos$ 的數值於 $cnt$ 之中的索引值 $idx$,再將 $idx$ 轉成對應的字母即可。
Python 程式碼
使用時間約為 1 s,記憶體約為 28.6 MB,通過測試。
def solve():
import sys
from bisect import bisect_left
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
n = int(data[ptr]) # 輸入 n 個字母
m = int(data[ptr + 1]) # 輸出 m 個字母
ptr += 2
s = data[ptr] # 字串內容
ptr += 1
cnt = [0] * 26 # 桶子排序,計數器,接下來要轉成前綴和
for c in s:
cnt[ord(c) - ord('A')] += 1
for i in range(1, 26):
cnt[i] += cnt[i - 1]
# 組合要輸出的字串
res = []
for _ in range(m):
pos = int(data[ptr])
ptr += 1
idx = bisect_left(cnt, pos)
res.append(chr(ord('A') + idx))
result.append("".join(map(str, res)) + "\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
使用時間約為 2.2 s,記憶體約為 28.7 MB,通過測試。
from bisect import bisect_left
while True:
try:
n, m = map(int, input().split()) # 輸入 n 個字母,輸出 m 個字母
except EOFError:
break
s = input() # 字串內容
cnt = [0] * 26 # 桶子排序,計數器,接下來要轉成前綴和
for c in s:
cnt[ord(c) - ord('A')] += 1
for i in range(1, 26):
cnt[i] += cnt[i - 1]
# 組合要輸出的字串
res = []
for pos in map(int, input().split()):
idx = bisect_left(cnt, pos)
res.append(chr(ord('A') + idx))
print("".join(map(str, res)))
C++ 程式碼
使用時間約為 33 ms,記憶體約為 19.3 MB,通過測試。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n, m;
string s, t;
vector<int> cnt;
while(cin >> n >> m) {
// 讀取字串 s,用桶子排序計算字母數量
cin >> s;
cnt.assign(26, 0);
for(char c : s) {
cnt[c - 'A']++;
}
// cnt 轉成前綴和,用於二分搜尋法
for(int i = 1; i < 26; i++) {
cnt[i] += cnt[i-1];
}
// 用二分搜尋法於 cnt 之中找第 p 個字母對應的索引值
t.clear();
for(int i = 0; i < m; i++) {
int p;
cin >> p;
int idx = lower_bound(cnt.begin(), cnt.end(), p) - cnt.begin();
t += char(idx + 'A'); // 一定能找到索引值
}
cout << t << "\n";
}
return 0;
}
沒有留言:
張貼留言