跳到正文

题解

题解 AT2672 【Coins】

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

文章信息

发布
2019年12月25日
收录
2026年3月31日
更新
2026年11月10日
篇幅
约 4 分钟

版本

  1. v1当前

提供一个用排序 + 优先队列的做法。

首先默认将三元组 (a,b,c)(a, b, c) 替换为二元组 (e=b−a,f=c−a)(e=b-a, f=c-a) (先默认所有人拿金币)。

然后问题转换为在 nn 个二元组中选 yy 个获得 ee 收益,选 zz 个获得 ff 收益,最大化总收益。

对于两个二元组 (ei,fi)(e_i, f_i), (ej,fj)(e_j, f_j) 假设 ii 选 ff 且 jj 选 ee ,

考虑什么时候交换他们的选择收益不会变少,也就是 ei+fj≥ej+fie_i + f_j \geq e_j + f_i ,

移项得 ei−fi≥ej−fje_i - f_i \geq e_j - f_j ,那么通过排序使得二元组按 e−fe - f 单调不降,

就有对于任意 i<ji < j ,如果 ii 选 ff 且 jj 选 ee ,那么交换两者状态一定不会变差。

换言之,存在最优解满足选 ee 的全在选 ff 的左边,

也就是说存在一个 kk 使得有最优解在 1 到 kk 中取 yy 个 ee 在 k+1k + 1 到 nn 中取 zz 个 ff 。

那么只需要通过优先队列预处理出每个前缀前 yy 大的 ee 的和以及每个后缀前 zz 大的 ff 的和。

然后枚举 kk 即可得出答案。

参考实现(代码中用 a,ba, b 表示的上述的 e,fe, f ):

C++
#include <cstdio>
#include <algorithm>
#include <queue>
#define debug(...) fprintf(stderr, __VA_ARGS__)

typedef long long ll;

struct {
	inline operator int () { int x; return scanf("%d", &x), x; }
	template<class T> inline void operator () (T &x) { x = *this; }
	template<class T, class ...A> inline void operator () (T &x, A &...a)
	{ x = *this; this -> operator ()(a...); }
} read;

const int maxn = 100005;
struct obj {
	int a, b;
};
obj ob[maxn];
ll lget[maxn], rget[maxn];

int main() {
	int x = read, y = read, z = read;

	int n = x + y + z;
	ll ans = 0;
	for(int i = 1; i <= n; i ++) {
		int v = read;
		ans += v;
		ob[i].a = read - v;
		ob[i].b = read - v;
	}

	std::sort(ob + 1, ob + n + 1, [](obj x, obj y) {
				return x.a - x.b > y.a - y.b;
			});

	std::priority_queue<int, std::vector<int>, std::greater<int> > biggest;

	for(int i = 1; i <= n; i ++) {
		lget[i] = lget[i - 1] + ob[i].a;
		biggest.push(ob[i].a);
		if(int(biggest.size()) > y) {
			lget[i] -= biggest.top();
			biggest.pop();
		}
	}

	while(!biggest.empty()) biggest.pop();
	for(int i = n; i; i --) {
		rget[i] = rget[i + 1] + ob[i].b;
		biggest.push(ob[i].b);
		if(int(biggest.size()) > z) {
			rget[i] -= biggest.top();
			biggest.pop();
		}
	}

	ll max = - 1000000000000000000;
	for(int k = y; k <= n - z; k ++)
		max = std::max(max, lget[k] + rget[k + 1]);

	printf("%lld\n", ans + max);
}
原文
存档评论25 条抓取于