您的位置:首页 > 其它

CodeForces - 1244E

2020-05-11 04:11 260 查看

You are given a sequence a1,a2,…,ana1,a2,…,an consisting of nn 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 kk times.

Input
The first line contains two integers nn and kk (2≤n≤105,1≤k≤1014)(2≤n≤105,1≤k≤1014) — 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,…,ana1,a2,…,an (1≤ai≤109)(1≤ai≤109).

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 kk 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
题意:
在有n个元素的序列中,对某个元素进行加一或者减一,你可以最多进行k次操作,问序列的极差最小可以为多少,
首先 极差=a[i] (max)-a[i] (min) 要是极差变小,只要是最大值与最小值尽可能的接近就好, 所以先排序,取出最小值和最大值,并且要看最大值元素有几个,最小值元素有几个,因为我们只可以进行k此操作,所以我们需要进行尽量的少的操作减小极差,举个列子 1 1… 7 显然极差是6,那么我们若要减小极差,可以使7减小或者1增大,若要让7减小只需要进行至少一次操作,若要让1增大至少需要两次操作,所以每次我们要进行操作时,先看最小元素和最大元素各有几个,对数量少的进行操作,直至最小值等于最大值,此时极差等于0,已达到最小,或者k次操作进行完。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
long long n,k,a[200200];
int main()
{
while(~scanf("%lld %lld",&n,&k))
{
for(long long i=0; i<n; i++)
scanf("%lld",&a[i]);
sort(a,a+n);
long long mi=a[0],ma=a[n-1],num1=1,num2=1;///num记录最小和最大值的数目
long long l=1,r=n-2,d=0;
while(mi!=ma&&k)
{
long long x1=(a[l]-mi)*num1;
long long x2=(ma-a[r])*num2;
if(num1==num2)
{
if(k>=x1)
{
mi=a[l];
num1++;
l++;
k-=x1;
}
else if(k>=x2)
{
ma=a[r];
r--;
num2++;
k-=x2;
}
else
{
d=k/num1;
k=0;
}
}
else if(num1>num2)
{
if(k>=x2)
{
ma=a[r];
r--;
num2++;
k-=x2;
}
else
{
d=k/num2;
k=0;
}
}
else
{
if(k>=x1)
{
mi=a[l];
num1++;
l++;
k-=x1;
}
else
{
d=k/num1;
k=0;
}
}
}
printf("%lld\n",ma-mi-d);
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e5+10;
ll a[N];
ll n,k,x,ans;
int main()
{
scanf("%lld %lld",&n,&k);
for(int i=1; i<=n; i++)
scanf("%lld",&a[i]);
sort(a+1,a+n+1);
for(int i=1; i<=n/2; i++)
{
int j=n-i+1;
x=(a[i+1]-a[i]+a[j]-a[j-1])*i;
if(x<=k)
k-=x;
else
{
ans=a[j]-a[i]-k/i;
break;
}
}
printf("%lld\n",ans);
return 0;
}
Starry_Sky_Dream 原创文章 50获赞 4访问量 2346 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: