Codeforces C. Ehab and Prefix MEXs (思維) (Round #649 Div.2)

傳送門

題意: 給定長度爲n的數組a,找到長度爲n的另一個數組b,使得:
對於每個i(1≤i≤n)MEX({b1,b2,…,bi})= ai。
一組整數的MEX是不屬於該組的最小非負整數。
如果這樣的數組不存在,輸出-1。
在這裏插入圖片描述
思路:

  • 爲了滿足a[i]是b1 ~ bi未出現的最小非負整數,則b[i]得爲ai ~ n未出現的儘量小的數。
  • 這便可以用set統計整個a數組中未出現的數,從1到n開始枚舉,每次取set的第一個元素,並將其刪除;若i >1時且a[i] != a[i - 1],還可以把a[i - 1]插入set內,以達到去儘量小的目的。

代碼實現:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e5 + 5;

int n, m;
int a[N], b[N];
map<int, int> vis;
set<int> tmp;

signed main()
{
    IOS;

    cin >> n;
    for(int i = 0; i < n; i ++){
        cin >> a[i];
        vis[a[i]] ++;
    }
    int m = n * 2;
    for(int i = 0; i < m; i ++)
        if(!vis[i]) tmp.insert(i);

    for(int i = 0; i < n; i ++){
        if(i && a[i] != a[i - 1]) tmp.insert(a[i - 1]);
        b[i] = *tmp.begin();
        tmp.erase(*tmp.begin());
    }

    for(int i = 0; i < n; i ++)
        cout << b[i] << " ";

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章