set/map作业解析

发布时间 2023-11-09 10:29:02作者: HelloHeBin

P761 【入门】明明的随机数

对于一组数据完成完成"去重"与"排序"的工作。

分析
方法1:可以直接排序后去重

点击查看代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 110;
int n, a[N],ans;

int main() {
    cin >> n;
    for (int i = 0; i < n; i++) cin >> a[i];
    sort(a, a + n);
    for (int i = 0; i < n; i++) {
        if (i == 0 || a[i] != a[i - 1])
            ans++;
    }
    cout<<ans<<endl;
    for (int i = 0; i < n; i++) {
        if (i == 0 || a[i] != a[i - 1])
            cout << a[i] << " ";
    }
    return 0;
}

方法2:利用set集合的特性,直接求入set中,再拿出来

点击查看代码
#include <bits/stdc++.h>
#include <set>
using namespace std;
typedef long long LL;

int main() {
    int n, x;
    set<int> s;
    cin >> n;
    while (n--) {
        cin >> x;
        s.insert(x);
    }
    cout << s.size() << endl;
    // 1. 迭代器遍历
    set<int>::iterator it = s.begin();
    for (; it != s.end(); it++)
        cout << *it << " ";
    cout << endl;
    // 2.  for each :   -std=C++11
    // for (auto u : s) cout << u << " "; cout << endl;
    // for (int u : s) cout << u << " "; cout << endl;
    return 0;
}

P760 [NOIP2007 提高组] 统计数字

P2814 数对

P495 【入门】宇宙总统1

P496 【入门】宇宙总统2

P2843 宇宙总统3

P2810 相邻字符对