P4083 题解

· · 题解

只用 STL 做到 \mathrm O(n\log n)

建图方式可以参考其他题解。由于每张饼只能用一次(BFS 中第一次遍历到一张饼时深度最小,在本题中即为最优),我们将所有饼存进 std::set。遍历过一张饼,就删除之,因为 std::set 中查找和迭代器累加都是 \mathrm O(\log n),一共 2n 张饼,就是 \mathrm O(n\log n)。

#include <cstring>
#include <iostream>
#include <set>
#include <queue>
#define F(var, start, end) for\
    (int var = (start), var##_done = (end); var <= var##_done; ++var)

const int oxis = 200003;

int score_self[oxis], // 制作饼的一方认为的美味度
    score_other[oxis], // 对方认为的美味度
    ans[oxis]; // 最小深度,即答案

// 使 std::set 中按对方认为的美味度排序,从而可以查找
struct compare {
    bool operator()(const int &u, const int &v) const {
        return  score_other[u] != score_other[v] ?
            score_other[u] <  score_other[v] : u < v;
    }
};

int main()
{
    std::ios::sync_with_stdio(false);
    int n, d;
    std::cin >> n >> d;
    memset(ans, 127, sizeof(ans));
    std::set<int, compare> bessie, elsie; // bessie 存 bessie 收到的饼
    std::queue<int> bfs;
    F (i, 1, n) {
        std::cin >> score_self[i] >> score_other[i];
        elsie.insert(i);
    }
    F (i, 1 + n, 2 * n) {
        std::cin >> score_other[i] >> score_self[i];
        bessie.insert(i);
    }
    F (i, 1, 2 * n)
        if (score_other[i] == 0) {
            bfs.push(i);
            ans[i] = 1;
            std::set<int, compare> &cow = i > n ? bessie : elsie;
            cow.erase(i);
        }
    while (!bfs.empty()) {
        int now = bfs.front();
        bfs.pop();
        int tastiness = score_self[now], depth = 1 + ans[now];
        std::set<int, compare> &cow = now > n ? elsie : bessie;
// 收到饼的美味度 >= 给出饼的美味度 - d
// 将下界放到 score_other[0] 以利用 lower_bound
        *score_other = tastiness - d;
        for (auto i = cow.lower_bound(0);
                i != cow.end() && score_other[*i] <= tastiness;
                cow.erase(i++)) {
            int received = *i;
            bfs.push(received);
            ans[received] = depth;
        }
    }
    F (i, 1, n)
        if (ans[i] == 2139062143)
            std::cout << "-1\n";
        else
            std::cout << ans[i] << '\n';
}