跳到正文

题解

题解:P12149 【MX-X11-T3】「蓬莱人形 Round 1」科学

smart_stupid约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年4月16日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 5 分钟
题目
P12149

版本

  1. v1当前

所以题目名字为什么不是 “空飛ぶ巫女の不思議な毎日”?

思路

首先,很显然,第一问答案小于等于 ⌈max⁡i=1nai2⌉\lceil\frac{\max\limits_{i=1}^n{a_i}}{2}\rceil,且满足单调性,所以二分答案第一问。我们将 AB 盒子排序后,假设答案为 xx,按以下方式放置:

将前 kk 小的盒子用 B 盒子装起来,且保证 kk 尽量大,将前 kk 大的盒子超过 xx 的部分分摊到空了的 kk 个 A 盒子里,剩下的 A 盒子将超过 xx 部分的用剩下的 B 盒子装起来。

所以我们这样写 check(我将 A 和 B 从大到小排序):

C++
bool check(int x) {
	for (int i = 1; i <= m; i++) b1[i] = b[i].b;
	int pos = m, k = 0;
	for (int i = n; i >= 1; i--) {
		while (pos > 0 && b1[pos] < a[i]) pos--;
		if (!pos) break; // 装不动了
		b1[pos] = 0, k++; // 被用过了
	}
	pos = 1;
	for (int i = k + 1; i <= n; i++) { // 忽略前 k 大的
		while (pos <= m && !b1[pos]) pos++;
		if (a[i] - b1[pos] > x) return 0;
		pos++;
	}
	return 1;
}

第一问出来了,第二问就直接把超过 xx 的部分放进 B 里面。由于 A 盒子可以乱放,所以只需要把超出 xx 的盒子减去 xx,再取这些盒子最小的那一部分,装进 B 里面,选哪些盒子可以用单调队列求解。

AC 代码:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, m, a[200100];
struct node{
	int b, w;
} b[200100];
int b1[200100];
bool cmp(node a, node b) {
	return a.b > b.b;
}
bool operator <(node a, node b) {
	return a.w > b.w;
}
priority_queue<node> pq;
bool check(int x) {
	for (int i = 1; i <= m; i++) b1[i] = b[i].b;
	int pos = m, k = 0;
	for (int i = n; i >= 1; i--) {
		while (pos > 0 && b1[pos] < a[i]) pos--;
		if (!pos) break; // 装不动了
		b1[pos] = 0, k++; // 被用过了
	}
	pos = 1;
	for (int i = k + 1; i <= n; i++) { // 忽略前 k 大的
		while (pos <= m && !b1[pos]) pos++;
		if (a[i] - b1[pos] > x) return 0;
		pos++;
	}
	return 1;
}
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) cin >> a[i];
	for (int i = 1; i <= m; i++) {
		cin >> b[i].b >> b[i].w;
	}
	sort(b + 1, b + m + 1, cmp);
	sort(a + 1, a + n + 1, greater<int>());
	int ans1 = 0, ans2 = 0;
	int l = a[1] / 2 + a[1] % 2, r = 1000000000;
	while (l < r) {
		int mid = (l + r) / 2;
		if (check(mid)) r = mid;
		else l = mid + 1;
	}
	ans1 = l;
	int cnt = 0; // 超出 x 盒子的数量
	for (int i = 1; i <= n; i++) {
		if (a[i] > ans1) a[i] -= ans1, cnt++;
	}
	sort(a + 1, a + n + 1);
	int pos = 1;
	for (int i = cnt; i >= 1; i--) {
		while (pos <= m && b[pos].b >= a[i]) { 
			pq.push(b[pos]);
			pos++;
		// 将可以装下当前 A 盒子的 B 盒子放进去。
		}
		if (!pq.empty()) {
			ans2 += pq.top().w;
			pq.pop();
		}
	}
	cout << ans1 << ' ' << ans2 << '\n';
	return 0;
}
原文