E. Minimum Array
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two arrays aa and bb, both of length nn. All elements of both arrays are from 00 to n−1n−1.
You can reorder elements of the array bb (if you want, you may leave the order of elements as it is). After that, let array cc be the array of length nn, the ii-th element of this array is ci=(ai+bi)%nci=(ai+bi)%n, where x%yx%y is xx modulo yy.
Your task is to reorder elements of the array bb to obtain the lexicographically minimum possible array cc.
Array xx of length nn is lexicographically less than array yy of length nn, if there exists such ii (1≤i≤n1≤i≤n), that xi<yixi<yi, and for any jj (1≤j<i1≤j<i) xj=yjxj=yj.
Input
The first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of elements in aa, bb and cc.
The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai<n0≤ai<n), where aiai is the ii-th element of aa.
The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (0≤bi<n0≤bi<n), where bibi is the ii-th element of bb.
Output
Print the lexicographically minimum possible array cc. Recall that your task is to reorder elements of the array bb and obtain the lexicographically minimum possible array cc, where the ii-th element of cc is ci=(ai+bi)%nci=(ai+bi)%n.
Examples
input
Copy
4 0 1 2 1 3 2 1 1
output
Copy
1 0 0 2
input
Copy
7 2 5 1 5 3 4 3 2 4 3 5 6 5 1
output
Copy
0 0 0 1 0 2 4
分析:因为元素的范围是0到n-1,所以对于任何一个a[i]来说,其最小值对于的b[i]应该是第一个大于等于n-a[i]。且要求字典序最小,那么直接从头开始找就行了,没找到的话就用剩余元素中最小的那个。multiset维护即可。
#include<bits/stdc++.h>
using namespace std;
int a[200004];
int b[200004];
int c[200004];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
multiset<int> s;
for (int i = 1; i <= n; ++i) {
scanf("%d", &b[i]);
s.insert(b[i]);
}
for (int i = 1; i <= n; ++i) {
int temp = n - a[i];
auto pos = s.lower_bound(temp);
if (pos == s.end()) {
c[i] = (a[i] + *s.begin());
s.erase(s.begin());
} else {
c[i] = (a[i] + *pos) % n;
s.erase(pos);
}
}
for (int i = 1; i <= n; ++i) {
printf("%d ", c[i]);
}
}