问题:
You are given a sequence a1,a2,…,an consisting of n integers.
You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.
Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.
Input
The first line contains two integers n and k (2≤n≤10^5,1≤k≤10^14) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.
The second line contains a sequence of integers a1,a2,…,an (1≤ai≤10^9).
Output
Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.
Examples
Input
4 5
3 1 7 5
Output
2
Input
3 10
100 100 100
Output
0
Input
10 9
4 5 5 7 5 4 5 2 4 3
Output
1
Note
In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3,3,5,5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2.
In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations.
题意:给两个数n,k;n表示有n个数,k表示有k次操作,每一次操作只能对一个数(任意数)加一或者减一,问在k次操作内,该数列的最大值与最小值差值最小为多少。
思路:首先排序,用map容器记录每个数出现的次数,然后从最小值和最大值开始遍历,如果最小值的数量小于最大值的数量则对最小值进行操作,反之则对最大值进行操作。一直到最大值相等与最小值,或者k小于0结束。
代码:
#include<stdio.h> #include<string.h> #include<map> #include<iostream> #include<algorithm> using namespace std; typedef long long ll; map<ll,ll>mp;//记录每个数出现的次数 ll a[210000]; int main() { ll n,k; scanf("%lld%lld",&n,&k); for(int i=1; i<=n; i++) { scanf("%lld",&a[i]); mp[a[i]]++; } sort(a+1,a+n+1);//从小到大排序 int x=1,y=n; ll ans=a[y]-a[x]; while(1) { if(a[x]==a[y])//如果最大值和最小值相等结束 { ans=0; break; } if(mp[a[x]]>mp[a[y]])//如果最小值的数量大于最大值的数量则对最小值进行操作 { ll sum=k-mp[a[y]]; ll tag=mp[a[y]]; if(sum<0) break; else { ll t=a[y]-a[n-tag]; if(t*tag<=k) { mp[a[n-tag]]+=mp[a[y]]; k=k-tag*t; y=n-tag; ans=a[y]-a[x]; } else { ll kk=k/tag; ans=a[y]-kk-a[x]; break; } } } else { ll sum=k-mp[a[x]]; ll tag=mp[a[x]]; if(sum<0) break; else { ll t=a[1+tag]-a[x]; if(t*tag<=k) { mp[a[1+tag]]+=mp[a[x]]; k=k-tag*t; x=1+tag; ans=a[y]-a[x]; } else { int kk=k/tag; ans=a[y]-kk-a[x]; break; } } } } printf("%lld\n",ans); }