跳到正文

题解

P14575 坤班

TheChariot约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
P14575

版本

  1. v1当前

这题还要二分吗?

先将老师们的信息存储在数组 colcol 和 mstmst 中,分别表示学科 ii 可以教几个班,有几个能当班主任。

那么答案的限制会有两个:

  1. ans≤min⁡i=1ncolians\le\min^{n}_{i=1}col_i。
  2. ans≤∑i=1nmstians\le\sum_{i=1}^{n}mst_i。

由于能当班主任的总人数是不变的,所以我们只能考虑使 min⁡i=1ncoli\min^{n}_{i=1}col_i 尽量大。

这里我们不用二分。

贪心地思考,不难发现每次选班主任的最优策略是取 max⁡i=1ncoli\max_{i=1}^{n}col_i,i∈{i∣msti>0}i\in\{i|mst_i>0\}。

那么只需要用优先队列维护,每次取堆顶的 colicol_i 和 ii,更新答案与 mstimst_i,如果 msti>0mst_i>0 则再加入优先队列,直到不满足以上两个限制之一。

由于每个班都必须有一个班主任,所以答案不超过 nn。时间复杂度 O(nlog⁡m)O(n\log m)。

code
C++
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 5e5+5;
ll col[N], mst[N];
int n, m;
priority_queue<pair<ll, int > >q;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		int a, b, c; cin >> a >> b >> c;
		col[a] += b;
		if (c) mst[a]++;
	}
	ll minn = 1e18;
	for (int i = 1; i <= m; i++) {
		minn = min(minn, col[i]);
	}
	for (int i = 1; i <= m; i++) {
		if (mst[i]) q.push({col[i], i});
	}
	int ans = 0;
	while (!q.empty() && minn > ans) {
		ll maxn = q.top().first;
		int id = q.top().second;
		q.pop();
		maxn--;mst[id]--;
		minn = min(minn, maxn);
		if (mst[id]) q.push({maxn, id});
		if (minn > ans) ans++;
	}
	cout << ans;
	return 0;
}
原文