← 所有笔记

E. Minimum Array codeforces (思维,二分,multiset)

E. Minimum Array 详解 思维,二分,multiset

题目传送门

思维部分:

遍历a 数组,对于a数组中的每一个元素在b数组中找到与之相加 >=n但是是最小的值,也就是第一个>= n - a[i]的值。 两者相加 mod n一定比原来的a[i]要小,自然就比a[i]加上任何一个<n-a[i]的值要更小。为什么呢?
a[i]能加的最大的数就是n-1,假设a[i]为x,最大的值就是:(x+n-1) % n ;
我们调换下顺序得到 ( (x-1) + n ) % n;
根据模运算得原式 = (x - 1) % n + n % n = x -1 < = x

multiset部分:

multiset 可以便捷的将b数组排序,并查找、删除所需要的数

二分部分:

用到了multiset 中的 lower_bound 函数 找到第一个大于等于所需值的 元素

AC代码:

#include<bits/stdc++.h>
using namespace std;

const int maxn = 2e5 + 5;
int a[maxn];
int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    multiset<int>st;
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i <= n; i++)
    {
        int temp;
        cin >> temp;
        st.insert(temp);
    }
    for (int i = 1; i <= n; i++)
    {
        int x = n - a[i];
        auto it = st.lower_bound(x); // auto 的妙用 不需要写一堆啦
        if (it == st.end()) it = st.begin();
        cout << (*it + a[i]) % n << ' ';
        st.erase(it);  // 通过迭代器删除元素
    }
    return 0;
}
✳

谢谢你读到这里。

更新于 2022-07-28

搜索笔记

搜索文章标题、标签和正文。

↑ ↓ 选择 · Enter 阅读Esc 关闭