【題解】ZeroJudge e836: P3. 數字統計 (Counting)

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=e836
TOI 新手同好會 歷屆考題

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

int n, a, cnt[20005], p[20005], mx;
vector <int> ans;
set <int> st;

bool cmp(int x, int y){
    return p[x+10000] < p[y+10000];
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++){
        cin >> a;
        cnt[a+10000]++;
        if (!p[a+10000]) p[a+10000] = i;
        st.insert(a);
    }
    mx = 2;
    for (int i = 0; i < 20005; i++){
        if (cnt[i] > mx){
            ans.clear();
            ans.push_back(i-10000);
            mx = cnt[i];
        }
        else if (cnt[i] == mx) ans.push_back(i-10000);
    }
    if (ans.empty()){
        cout << n << "\nNO\n";
        return 0;
    }
    sort(ans.begin(), ans.end(), cmp);
    cout << st.size() << "\n";
    for (int i:ans){
        cout << i << " ";
    }
}

Python code (credit: Amy Chou)

N = int(input())
num = list(map(int, input().split()))
dic  = {}
st = set()
mx  = 0
for n in num:
    st.add(n)
    dic[n] = dic.get(n, 0) + 1
    mx = max(mx, dic[n])

print(len(st))
if len(st) < len(num):
    for k, v in dic.items():
        if v == mx:
            print(f"{k} ", end = "")
else:
    print("NO")
分享本文 Share with friends