Codeforces Round #592 (Div. 2), problem: (E) Minimizing Difference贪心
题意:最多进行k个操作,每次操作对一个数-1,问最后数组的最大值和最小值差的最小值
做法:比较使当前最小值+1和使最大值-1对k的减少量,即等于最小值的有几个数,等于最大值的有多少个数
但是仅仅这么做会超时(
1
e
9
1e^9
1e9),所以还要一个位置left判断最小值能不能加到第二小的数,一个位置right判断最大值能不能减到第二大的数
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#include<map>
#define ll long long
#define pb push_back
#define rep(x,a,b) for (int x=a;x<=b;x++)
#define repp(x,a,b) for (int x=a;x<b;x++)
#define W(x) printf("%d\n",x)
#define WW(x) printf("%lld\n",x)
#define pi 3.14159265358979323846
#define mem(a,x) memset(a,x,sizeof a)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int maxn=2e6+7;
const int INF=1e9;
const ll INFF=1e18;
ll a[maxn];
int main()
{
ll n,k,num1=1,num2=1,minn,maxx,left,right,d=0;
scanf("%lld%lld",&n,&k);
rep(i,1,n)scanf("%lld",&a[i]);
sort(a+1,a+1+n);
minn=a[1];maxx=a[n];
left=2;right=n-1;
while(maxx!=minn&&k)
{
ll x1=(a[left]-minn)*num1;
ll x2=(maxx-a[right])*num2;
if (num1==num2)
{
if (k>=x1)
{
minn=a[left];
left++;
num1++;
k-=x1;
}
else if (k>=x2)
{
maxx=a[right];
right--;
num2++;
k-=x2;
}
else
{
d+=k/num1;
k=0;
}
}
else if (num1>num2)
{
if (k>=x2)
{
maxx=a[right];
right--;
num2++;
k-=x2;
}
else
{
d+=k/num2;
k=0;
}
}
else
{
if (k>=x1)
{
minn=a[left];
left++;
num1++;
k-=x1;
}
else
{
d+=k/num1;
k=0;
}
}
}
WW(maxx-minn-d);
}