Codeforces Round #649 (Div. 2) C. Ehab and Prefix MEXs
题目链接
Given an array a of length n, find another array, b, of length n such that:
- for each i (1≤i≤n) MEX({b1, b2, …, bi})=ai.
The MEX of a set of integers is the smallest non-negative integer that doesn’t belong to this set.
If such array doesn’t exist, determine this.
Input
The first line contains an integer n (1≤n≤1e5) — the length of the array a.
The second line contains n integers a1, a2, …, an (0≤ai≤i) — the elements of the array a. It’s guaranteed that ai≤ai+1 for 1≤i<n.
Output
If there’s no such array, print a single line containing −1.
Otherwise, print a single line containing n integers b1, b2, …, bn (0≤bi≤1e6)
If there are multiple answers, print any.
Examples
input
3
1 2 3
output
0 1 2
input
4
0 0 0 2
output
1 3 4 0
input
3
1 1 3
output
0 2 1
cf 典型构造题~
首先我们考虑输出 -1 的情况,只有两种,一是 ,二是 ,题目保证了样例不存在以上两种情况,所有不存在输出为 -1 的情况~
下面考虑构造,我们首先将答案数组的所有数置为 ,然后只需考虑修改数组即可。对 的情况可以直接跳过,而对 的时,我们必须要考虑修改数组,对每个 ,要保证 出现在数组中,那么我们可以用 记录不在答案数组中的最小元素,那么只需往里面插入 即可,我们可以从当前位置 往前递减插入,但这里有个坑点:
对位置 ,当 时,不能插入,因为这会影响前面答案的正确性
AC代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
main(){
int n;
cin>>n;
int a[n+1]={0},ans[n+1],mx=0;
fill(ans,ans+n+1,n+1);
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++){
if(a[i]>a[i-1]){
int pos=i,k=mx;
while(mx<a[i]){
if(ans[pos]>=k) ans[pos]=mx,mx++,pos--;
else pos--;
}
}
}
for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
}