题解:P14132 【MX-X22-T3】「TPOI-4C」Another MEX Problem

· · 题解

前言:

还是 STL 大佬。

分析:

这个题十分甚至九分的难读,考虑转化一下,大致就是有一个值域线段,第 i 个询问就是从 a_i 处劈开。你可以最多使用 m 次操作从任意位置劈开,需要求最小的 x 使得 [x,x+k) 这个值域里面都没有被劈开。

然后我们发现,对于一个长度为 \mathcal{l} 的线段,你需要用掉 \left \lfloor \frac{\mathcal{l}}{k} \right \rfloor 次操作机会才能使得不存在一段长度为 k 的区间,使得这里面的数都没有被劈开。

每次劈开用 set 模拟,统计答案遍历整个 set 可以维护上述操作,时间复杂度 \mathcal{O(n^2\log n)}。

然后我们发现,这个下取整是一个很好的性质,他直接决定了你的答案是单调不降的,因为区间的操作次数越劈越小。

那么你就可以维护前面一段答案使用了几次操作,然后从上一次答案处出发继续遍历 set。由于遍历裂开的区间是 \mathcal{O(n)} 级别的,然后加上 set 的操作,总复杂度就是 \mathcal{O(n\log n)} 的。

# include <iostream>
# include <algorithm>
# include <set>
# include <map>
# define int long long 
using namespace std ;
constexpr int N = 2e5 + 5 , INF = 9e18 ;
int n , m , k , a[N] ;
void solve () {
    cin >> n >> m >> k ; 
    map < int , int > tot ; 
    for ( int i = 1;i <= n;++i ) cin >> a[i] ;
    set < int > dd ; 
    dd.insert ( -1 ) , dd.insert ( INF ) ;
    int ans = 0 , rm = 0 ; 
    for ( int i = 1;i <= n;++i ) {
        tot[a[i]] ++ ; 
        if ( tot[a[i]] == 1 ) {
            set < int >::iterator pr = ( -- dd.lower_bound ( a[i] ) ) ; 
            set < int >::iterator nx = dd.upper_bound ( a[i] ) ; 
            if ( *nx < ans ) rm -= ( *nx - *pr - 1 ) / k , rm += ( *nx - a[i] - 1 ) / k ;
            if ( a[i] < ans ) rm += ( a[i] - *pr - 1 ) / k ;
            dd.insert ( a[i] ) ;
        }
        set < int > :: iterator it = ( dd.lower_bound ( ans ) ) ; int now = rm ;
        // cerr << rm << ' ' << *(it) << ' ' << ans << '\n' ;
        for ( ; it != dd.end();++it ) {
            set < int > :: iterator pre = ( -- it ) ++ ;
            // cerr << *pre << " " << *it << ' ' << i << '\n' ;
            if ( now + ( *it - *pre - 1 ) / k > m ) { ans = *pre + 1 + ( m - now ) * k , rm = now ; break ; }
            now += ( *it - *pre - 1 ) / k ; 
        }
        cout << ans << ' ' ;
    } 
    cout << '\n' ;
}
signed main () {
    ios::sync_with_stdio(false) , cin.tie(0) , cout.tie(0) ;
    int T ; cin >> T ; while ( T-- ) solve () ; 
}