题目
给出n个正整数,最多执行k次操作。每次操作可以选择一个数加一或减一。问操作后最小值和最大值的最小差值是多少。
求解
贪心。
每次肯定选择最小值加一或者最大值减一。选哪一个取决于最小值的数量少还是最大值的数量少。假设最大值有x个,那么我们得将这x个最大值都减1才能使最终贡献减一,最小值同理。因此不断贪心合并即可。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
void solve()
{
int n;
long long k;
scanf("%d %lld", &n, &k);
map<int, int> mp;
for (int i = 1; i <= n; i++)
{
int temp;
scanf("%d", &temp);
mp[temp]++;
}
while (1)
{
auto it1 = mp.begin();
int mn = it1->first;
int mn_num = it1->second;
auto it2 = mp.rbegin();
int mx = it2->first;
int mx_num = it2->second;
if (mn == mx)
{
printf("0\n");
return;
}
if (k < min(mn_num, mx_num))
break;
if (mn_num < mx_num)
{
it1++;
int val = it1->first;
int times = min(1ll * val - mn, k / mn_num);
k -= 1ll * times * mn_num;
mp[mn + times] += mp[mn];
mp.erase(mn);
}
else
{
it2++;
int val = it2->first;
int times = min(1ll * mx - val, k / mx_num);
k -= 1ll * times * mx_num;
mp[mx - times] += mp[mx];
mp.erase(mx);
}
}
int mn = mp.begin()->first;
int mx = mp.rbegin()->first;
printf("%d\n", mx - mn);
}
int main()
{
solve();
return 0;
}