题解:P17178 Code Code Patch Crash

· · 题解

题意:

给了 n 个层,每一层的范围是 \left[l_i, r_i\right]。某一层不能到达另一层当且仅当两层的范围无交集。我们可以任意调换层级的顺序,并可以合并相邻层。问在能阻止 bug 从第 1 层到达第 n 层的前提下,最少需要几层(合并两层后算一层)。

思路:

首先我们要明确,答案只可能为 0 或 2 或 3。

考虑证明:

至此,我们只要对所有层做区间合并,判断独立大区间数目,便可得出结果了。

AC 代码:

#include<bits/stdc++.h>
#define PII pair<int, int>
using namespace std;
int t, n, m;
vector<PII> v;
int merge(vector<PII> v) {
    int sum = 0;
    sort(v.begin(), v.end());
    int st = -1e9, ed = -1e9;

    for (auto p : v) {
        if (ed < p.first) {
            if (st != -1e9) {
                sum++;
            }

            st = p.first, ed = p.second;
        } else {
            ed = max(ed, p.second);
        }
    }

    if (st != -1e9) {
        sum++;
    }

    return sum;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> t;

    while (t--) {
        cin >> n >> m;
        int mxl = 0, mnr = 1e9;
        v.clear();

        for (int i = 1; i <= n; i++) {
            int l, r;
            cin >> l >> r;
            mxl = max(mxl, l);
            mnr = min(mnr, r);
            v.push_back({l, r});
        }

        int cnt = merge(v);

        if (mxl <= mnr) {
            cout << 0 << '\n';
        } else if (cnt == n) {
            cout << 2 << '\n';
        } else {
            if (cnt == 1) {
                cout << 3 << '\n';
            } else {
                cout << 2 << '\n';
            }
        }
    }

    return 0;
}