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]<<" ";
}