Codeforces Round #555 (Div. 3)E. Minimum Array

題目鏈接

You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n−1.

You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is ci=(ai+bi)%n, where x%y is x modulo y.

Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.

Array x of length n is lexicographically less than array y of length n, if there exists such i (1≤i≤n), that xi<yi, and for any j (1≤j<i) xj=yj.

Input
The first line of the input contains one integer n (1≤n≤2⋅105) — the number of elements in a, b and c.

The second line of the input contains n integers a1,a2,…,an (0≤ai<n), where ai is the i-th element of a.

The third line of the input contains n integers b1,b2,…,bn (0≤bi<n), where bi is the i-th element of b.

Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is ci=(ai+bi)%n.

Examples
inputCopy
4
0 1 2 1
3 2 1 1
outputCopy
1 0 0 2
inputCopy
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
outputCopy
0 0 0 1 0 2 4

題意: 兩個長度爲n的數組,數組a位置不變,改變數組b的位置,構造數組c ci=(ai+bi)%n,使得數組c字典序最小。
思路: 使得數組c的字典序最小,即每次bi使得ai+bi大於n並且最接近n,因此用multiset維護數組b,lower_bound(n-a[i])即可。

#include<bits/stdc++.h>
using namespace std;
#define sc(x)   scanf("%d",&x)
int a[210000],b[210000];
multiset<int>mu;
int main()
{
    int n;
    sc(n);
    for(int i=0;i<n;i++)    sc(a[i]);
    for(int i=0;i<n;i++){int x;sc(x);mu.insert(x);};
    multiset<int>::iterator it;
    for(int i=0;i<n;i++){
        it = mu.lower_bound(n-a[i]);
        if(it == mu.end())  it = mu.begin();
        cout<<(a[i]+*it)%n<<" ";
        mu.erase(it);
    }
    cout<<endl;
    return 0;
}

發佈了48 篇原創文章 · 獲贊 2 · 訪問量 3032
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章