跳到正文

题解

题解:P3963 [TJOI2013] 奖学金

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

文章信息

发布
2026年10月7日
收录
2026年10月11日
更新
2026年11月15日
篇幅
约 5 分钟
题目
P3963

版本

  1. v1当前

Link

闲话

ps:最近学习了一下主席树,于是写一下这道题来巩固知识。

(其实这道题主席树不是最优解,但是可以用来练习主席树)

不说废话了,直接说重点好了。

题意简述

有 cc 个人,他们有两个属性费用 bib_i 和贡献 aia_i,问你在这 cc 个人中选 nn 个人,在满足费用和不超过 ff 的情况下这 nn 个人贡献值的中位数最大是多少。

先按 aia_i 从小到大排序肯定是没有问题的。

注意到这题和中位数有关,那么我们可以枚举这个中位数 vv,然后找贡献比 vv 小的前 n−12\frac{n - 1}{2} 个费用小的人和贡献比 vv 大的前 n−12\frac{n - 1}{2} 个费用小的人,然后计算一下费用和是否超过 ff,没有超过就更新 ansans。

至于如何找第 kk 大的数显然可以用主席树维护,然后这道题就做完了。

AC 代码
C++
// Problem: P3963 [TJOI2013] 奖学金
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3963
// Memory Limit: 125 MB
// Time Limit: 1000 ms

#include <bits/stdc++.h>

namespace Qwarth {

using i64 = long long;

const int N = 200007;

int n, c, tot;
i64 f;
int root[N];
i64 lsh[N], L;
std::pair< i64, i64 > stu[N];

struct node {
	int l, r, s;
	i64 f;
} t[N << 5];

int ID(int v) {
	return std::lower_bound(lsh + 1, lsh + L + 1, v) - lsh;
}

int build(int l, int r) {
	int rt = ++tot;
	if (l != r) {
		int mi = (l + r) >> 1;
		t[rt].l = build(l, mi);
		t[rt].r = build(mi + 1, r);
	}
	return rt;
}

int update(int k, int l, int r, int lt) {
	int rt = ++tot;
	t[rt].s = t[lt].s + 1;
	t[rt].f = t[lt].f + lsh[k];
	if (l != r) {
		int mi = (l + r) >> 1;
		if (k <= mi) {
			t[rt].l = update(k, l, mi, t[lt].l);
			t[rt].r = t[lt].r;
		} else {
			t[rt].l = t[lt].l;
			t[rt].r = update(k, mi + 1, r, t[lt].r);
		}
	}
	return rt;
}

i64 query(int k, int l, int r, int x, int y) {
	if (l == r) {
		return k * lsh[l];
	}
	int sum = t[t[y].l].s - t[t[x].l].s;
	int mi = (l + r) >> 1;
	if (k <= sum) {
		return query(k, l, mi, t[x].l, t[y].l);
	} else {
		return t[t[y].l].f - t[t[x].l].f + query(k - sum, mi + 1, r, t[x].r, t[y].r);
	}
}

void main() {
	std::cin >> c >> n >> f;
	for (int i = 1; i <= n; ++i) {
		std::cin >> stu[i].first >> stu[i].second;
		lsh[i] = stu[i].second;
	}
	std::sort(stu + 1, stu + n + 1);
	std::sort(lsh + 1, lsh + n + 1);
	L = std::unique(lsh + 1, lsh + n + 1) - (lsh + 1);
	root[0] = build(1, L);
	for (int i = 1; i <= n; ++i) {
		root[i] = update(ID(stu[i].second), 1, L, root[i - 1]);
	}
	i64 ans = -1;
	for (int i = (c - 1) / 2 + 1; i <= n - (c / 2); ++i) {
		i64 ls = query(c / 2, 1, L, root[0], root[i - 1]);
		i64 rs = query(c / 2, 1, L, root[i], root[n]);
		if (ls + rs + stu[i].second <= f) {
			ans = std::max(ans, stu[i].first);
		}
	}
	std::cout << ans << '\n';
}
}  // namespace Qwarth

int main() {
	// freopen(".in", "r", stdin);
	// freopen(".out", "w", stdout);
	std::ios::sync_with_stdio(0), std::cin.tie(0);
	int _T = 1;
	// std::cin >> _T;
	while (_T--) {
		Qwarth::main();
	}
	return 0;
}
原文