这题还要二分吗?
先将老师们的信息存储在数组 和 中,分别表示学科 可以教几个班,有几个能当班主任。
那么答案的限制会有两个:
- 。
- 。
由于能当班主任的总人数是不变的,所以我们只能考虑使 尽量大。
这里我们不用二分。
贪心地思考,不难发现每次选班主任的最优策略是取 ,。
那么只需要用优先队列维护,每次取堆顶的 和 ,更新答案与 ,如果 则再加入优先队列,直到不满足以上两个限制之一。
由于每个班都必须有一个班主任,所以答案不超过 。时间复杂度 。
code
#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;
}