题解:P5894 [IOI 2013] robots 机器人

· · 题解

P5894 [IOI 2013] robots 机器人

二分答案。

题目大意

有 a 个弱机器人,第 i 个只能运重量不大于 x_i 的物品;有 b 个小机器人,第 i 个只能运体积不大于 y_i 的物品。有 t 个物品,第 i 个物品重 w_i,体积为 s_i。

需要运送所有 t 个物品,最小化使用次数最多的机器人的次数。

题意分析

由题目分析出关键词“最小化最大值”,可以使用二分答案二分最小值。可以先从弱机器人入手,容易分析得到两个物品都能被同一个弱机器人运走,二选一选体积大的物品一定不劣。因为选体积小的物品留下体积大的可能会在小机器人运送时出现没有小机器人能运体积大的那个物品并不是最优。

同时,为保证限制大的弱机器人不会被重量小的物品占用次数,应该将弱机器人限制从小到大排序,并且将物品按重量从小到大排序,小的配小的,大的配大的。

遍历弱机器人,将没有被选择且能被当前机器人选择的物品的体积入大根堆,每个弱机器人一定将次数使用完,取堆顶,即体积大的运走。

剩下的物品用小机器人送,由于堆顶是体积最大的物品,所以小机器人应该按限制从大到小排序,同样地,大的配大的,小的配小的。

时间复杂度 \mathcal{O}(T \log^2 T)。

代码实现

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#ifdef OFFLINE_RUN
struct Timer { 
    chrono::high_resolution_clock::time_point start; 
    Timer() { start = chrono::high_resolution_clock::now(); } 
    ~Timer() { 
        auto end = chrono::high_resolution_clock::now(); 
        auto duration = chrono::duration_cast<chrono::milliseconds>(end - start); 
        fprintf(stderr, "\033[32m%lldms\033[0m\n", 1ll * duration.count()); 
} } timer;
#endif

const int T = 1e6 + 10, R = 5e4 + 10;
struct toy {
    int w, s;
    toy() {}
    toy(int w, int s) : w(w), s(s) {}
} p[T];
int x[R], y[R];
int a, b, t;
priority_queue<int> q;

bool chk(int limit) {
    while (!q.empty()) {
        q.pop();
    }
    int cur = 1;
    for (int i = 1; i <= a; i++) { // weak(weight) robot
        while (cur <= t && p[cur].w < x[i]) {
            q.push(p[cur++].s);
        }
        int cnt = 0;
        while (!q.empty() && cnt++ < limit) {
            q.pop();
        } 
    }
    while (cur <= t) {
        q.push(p[cur++].s);
    }
    for (int i = 1; !q.empty() && i <= b; i++) { // small(size) robot
        int cnt = 0;
        while (!q.empty() && q.top() < y[i] && cnt++ < limit) {
            q.pop();
        }
    }
    return q.empty();
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> a >> b >> t;
    for (int i = 1; i <= a; i++) {
        cin >> x[i];
    }
    for (int i = 1; i <= b; i++) {
        cin >> y[i];
    }
    for (int i = 1, w, s; i <= t; i++) {
        cin >> w >> s;
        p[i] = toy(w, s);
    }
    sort(x + 1, x + a + 1); // weak(weight) low->high
    sort(y + 1, y + b + 1, greater<int>()); // small(size) high->low
    sort(p + 1, p + t + 1, [](toy x, toy y) {
        return x.w < y.w;
    }); // toy.weight low->high
    int l = 1, r = t, ans = -1;
    while (l <= r) {
        int mid = l + r >> 1;
        if (chk(mid)) {
            r = mid - 1;
            ans = mid;
        } else {
            l = mid + 1;
        }
    }
    cout << ans << endl;
    return 0;
}

AC Record