【題解】ZeroJudge b130: NOIP2006 1.明明的随机数

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=b130

【作法-1】array

  • 用一個array a[x] 來紀錄每一個 x 出現的次數,1 ≤ x ≤ 1000。
#include <iostream>
using namespace std;

int main() {
    int N, x;
    cin >> N;
    int a[1001]; //N个1到1000之间的随机整数
    for (int i = 0; i <= 1000; i++) {
        a[i] = 0; //初始化
    }
    for (int i = 0; i < N; i++) {
        cin >> x;
        a[x]++;
    }
    int ans = 0;
    for (int i = 1; i <= 1000; i++) {
        if (a[i]) ans++;
    }
    cout << ans << "\n";
    for (int i = 1; i <= 1000; i++) {
        if (a[i]) cout << i << " ";
    }
    cout << "\n";
    return 0;
}

【作法-2】map

#include <iostream>
#include <map>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int N, x;
    while (cin >> N){
        map<int,int> mp;
        for (int i=0; i<N; i++){
            cin >> x;
            if (mp.count(x)) mp[x]++;
            else mp[x] = 1;
        }
        cout << mp.size() << '\n';
        for (auto it=mp.begin(); it!=mp.end(); it++){
            cout << (*it).first << ' ';
        }
        cout << '\n';
    }
    return 0;
}

Python code (credit: Amy Chou)

N = int(input())
lst = list(map(int, input().split()))
lst = list(set(lst))
lst.sort()
print(len(lst))
print(" ".join(list(map(str, lst))))
分享本文 Share with friends