目录
一、题目
1、题目描述
2、输入输出
2.1输入
2.2输出
3、原题链接
C - Perform Operations to Maximize Score
二、解题报告
1、思路分析
昨晚没打,看好多人说C题有点东西过来看下
其实前不久有一场就是中位数二分,可能对中位数check不太敏感
先将数组非降序排序然后贪心的考虑两种可能的答案:
k 次 全加到最大值上面然后删除最大值,答案就是nums[n - 1] + mid(n - 1)
删除最大值,然后k次操作用来尽可能最大化mid(n - 1)
第一种情况直接排序就能得到
第二种情况我们如何最大化mid(n - 1)?
我们只需二分一下最大的mid,如何check?
O(N)判断一个数x是否可以成为中位数:我们可以在k次操作内从数组中拿出 w 个大于等于x的数,其中w * 2 > n - 1
2、复杂度
时间复杂度: O(NlogU)空间复杂度:O(N)
3、代码详解
#include <bits/stdc++.h>
#include <ranges>
// #define DEBUG
using i64 = long long;
using u32 = unsigned;
using u64 = unsigned long long;
constexpr int inf32 = 1E9 + 7;
constexpr i64 inf64 = 1E18 + 7;
constexpr double eps = 1E-9;
void solve() {
int n, k;
std::cin >> n >> k;
std::vector<std::array<int, 2>> a(n);
for (int i = 0; i < n; ++ i)
std::cin >> a[i][0];
for (int i = 0; i < n; ++ i)
std::cin >> a[i][1];
std::ranges::sort(a, [](auto& x, auto& y) -> bool {
return x[0] < y[0];
});
auto check = [&](i64 m) -> bool {
int w = 0, c = 0;
for (int i = n - 2; ~i; -- i) {
if (a[i][0] >= m)
++ w;
else if(a[i][1]) {
int inc = m - a[i][0];
if (c + inc <= k)
c += inc, ++ w;
else
break;
}
}
return w * 2 > n - 1;;
};
i64 lo = 0, hi = 2E9 + 1;
while (lo + 1 < hi) {
i64 x = lo + hi >> 1;
if (check(x))
lo = x;
else
hi = x;
}
i64 res = lo + a[n - 1][0];
bool ok = false;
for (int i = n - 1; ~i; -- i) {
if (a[i][1]) {
std::swap(a[n - 1], a[i]);
ok = true;
break;
}
}
if (ok) {
std::sort(a.begin(), a.end() - 1, [](auto& x, auto& y) -> bool {
return x[0] < y[0];
});
res = std::max(res, 1LL * a[n - 1][0] + a[(n - 2) / 2][0] + k);
}
std::cout << res << '\n';
}
auto FIO = []{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
} ();
int main() {
#ifdef DEBUG
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int t = 1;
std::cin >> t;
while (t --)
solve();
return 0;
}