a427中等字串統計・複合比較鍵
APCS 2018/10:最少相異字母 (ZeroJudge e313)
依相異字母數優先、字典序次之,維護目前最佳字串。
這題在學什麼
對每個字串建立字母集合,集合大小就是相異字母數。例如 ABBCAAB 雖有七個字元,相異字母只有 A、B、C 三種。大寫字母只有 26 種,可用布林陣列或集合線性掃描計算。
比較兩個候選時先比相異字母數,數量較少者勝;相同時直接比較原字串的字典序。依這個二層比較規則,只需保存目前最佳字串,每次取較佳者,最後就等同在所有輸入中取最小比較鍵。不能把字母排序後的字串拿來破同分。
Step-by-step animation
公開範例:ABBCAAB、AABBACC、AAPPCCSS
步驟 1 / 3
第一個候選
ABBCAAB 的集合是 {A,B,C},先作為目前答案。
ABBCAAB
A:有
B:有
C:有
- 相異數
- 3
- best
- ABBCAAB
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n; cin >> n;
string best;
int bestCount=27;
for (int i=0;i<n;i++) {
string s; cin >> s;
array<bool,26> seen{};
int count=0;
for (char c:s) {
if (!seen[c-'A']) { seen[c-'A']=true; ++count; }
}
if (count<bestCount || (count==bestCount && s<best)) {
bestCount=count;
best=s;
}
}
cout << best << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。