跳到正文

题解

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

zjsdut约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年10月6日
收录
2026年10月18日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
8
题目
P14132

版本

  1. v1当前

把已有的数存到一个 std::set<int> 里。

假想一开始有一个数 −1-1。

从左往右填相邻两数之间的空白,这里“空白”指缺的数。设 a,ba, b 是相邻的两个数,二者之间缺少 b−a−1b - a - 1 个数,需要填 ⌊(b−a−1)/k⌋\lfloor (b-a-1)/k \rfloor 个数。

设最后一段被填好的空白是 AA 和 BB 之间的空白,此时还可以再加 CC 个数,那么答案是 B+Ck+1B + Ck + 1。

我们维护 BB 和 CC。一开始 B=−1B = -1,C=mC = m。

如果下一个数 xx 以前没出现过且 x<Bx < B,设 xx 在已有的相邻两数 ll 和 rr 之间,那么将会省下

⌊(r−l−1)/k⌋−(⌊(x−l−1)/k⌋+⌊(r−x−1)/k⌋)\lfloor (r - l -1) / k \rfloor - (\lfloor (x - l -1) / k \rfloor + \lfloor (r - x - 1) / k \rfloor)

个数。

加入 xx 后,看 BB 能否增大,即 BB 和它的下一个数之间的空白能否被填好。

代码
C++
#include <bits/stdc++.h>
using namespace std;

void solve() {
    int n, m, k;
    cin >> n >> m >> k;
    set<int> s = {-1}; // 已有的数
    auto ptr = s.begin();
    int more = m; // 还可以添加多少个数
    // 答案是 *ptr + 1 + (long long) more * k
    
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        auto [p, ok] = s.insert(x);
        if (ok && x < *ptr) {
            int l = *prev(p);
            int r = *next(p);
            more += (r - l - 1) / k - ((x - l - 1) / k + (r - x - 1) / k);
        }
        while (next(ptr) != s.end() && (*next(ptr) - *ptr - 1) / k <= more) {
            more -= (*next(ptr) - *ptr - 1) / k;
            ++ptr;
        }
        cout << *ptr + 1 + (long long) more * k << ' ';
    }
    cout << '\n';
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T;
    cin >> T;
    while (T--) {
        solve();
    }
}
原文
存档评论3 条抓取于