跳到正文

题解

P4083 题解

物灵约 4 分钟
原文
文章信息与版本

文章信息

发布
2022年3月16日
收录
2026年9月29日
更新
2026年11月15日
篇幅
约 4 分钟
获赞
5
题目
P4083

版本

  1. v1当前

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

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

C++
#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';
}
原文
抓取于
  1. Vector_Li

    有点像 USACO 官方的思路,很清晰

  2. Harp_Skier

    拜谢STL