結果

問題 No.1526 Sum of Mex 2
ユーザー V_Melville
提出日時 2026-08-09 17:54:55
言語 C++23
(gcc 15.2.0 + boost 1.90.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 60 ms / 3,000 ms
+ 285µs
コード長 1,753 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 2,975 ms
コンパイル使用メモリ 343,520 KB
実行使用メモリ 8,064 KB
最終ジャッジ日時 2026-08-09 17:55:01
合計ジャッジ時間 5,284 ms
ジャッジサーバーID
(参考情報)
judge3_1 / judge2_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)

using namespace std;
using ll = long long;

map<int, int> mp;

auto split(int x) {
    auto it = mp.upper_bound(x);
    --it;
    if (it->first == x) return it;
    return mp.insert({x, it->second}).first;
}

int get(int x) {
    return prev(mp.upper_bound(x))->second;
}

int main() {
    int n;
    cin >> n;

    vector<int> a(n);
    rep(i, n) cin >> a[i];
    
    vector<int> m(n);
    vector<bool> vis(n+2);
    int mex = 1;
    rep(i, n) {
        vis[a[i]] = true;
        while (vis[mex]) ++mex;
        m[i] = mex;
    }

    vector<int> nxt(n);
    vector<int> last(n+2, n);
    for (int i = n-1; i >= 0; --i) {
        nxt[i] = last[a[i]];
        last[a[i]] = i;
    }
    
    ll now = 0;
    rep(i, n) {
        now += m[i];
        if (i == 0 or m[i] != m[i-1]) {
            mp[i] = m[i];
        }
    }
    mp[n] = 0;
    
    ll ans = 0;
    rep(l, n) {
        ans += now;
        
        int x = a[l];
        int r = nxt[l]-1;
        
        int ac = r+1, wa = l-1;
        while (ac-wa > 1) {
            int wj = (ac+wa)/2;
            if (get(wj) > x) ac = wj; else wa = wj;
        }
        
        int k = ac;
        if (k <= r) {
            auto itr = split(r+1);
            auto itl = split(k);
            
            for (auto it = itl; it != itr; ++it) {
                int nl = it->first;
                int nr = next(it)->first-1;
                int nx = it->second;
                now -= ll(nr-nl+1)*nx;
            }
            
            mp.erase(itl, itr);
            mp[k] = x;
            
            now += ll(r-k+1)*x;
        }
        
        now -= get(l);
    }
    
    cout << ans << '\n';
    
    return 0;
}
0