有几个数,比如2 4 4 7,给一个数k,k如何分配(每个数可能会加上k分配的那部分)使得这几个数差值最小,比如7 6 4,k=4时,k分1给6,分3给4,k被分完,此时这三个数是7 7 7,差值最小
ll a[N];
ll b[N];
void insert(ll l, ll r, ll c)
{
b[l] += c;
b[r + 1] -= c;
}
ll n, k;
cin >> n >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + 1 + n);
for (int i = 1; i <= n; i++) insert(i, i, a[i]);
for (int i = 2; i <= n; i++)
{
if (k == 0) break;
if (a[i] > a[i - 1])
{
ll ca = a[i] - a[i - 1];
if (k >= ca * (i - 1))
{
k -= ca * (i - 1);
insert(1, i - 1, ca);
}
else
{
int ze = k / (i - 1);
int yu = k % (i - 1);
if (ze) insert(1, i - 1, ze);
insert(1, yu, 1);
k = 0;
}
}
}
if(k!=0)
{
int cu=k/n;
int yu=k%n;
if(cu>0)
{
for(int i=1;i<=n;i++)
{
a[i]+=cu;
if(yu>0) a[i]++,yu--;
}
}
else
{
for(int i=1;i<=n;i++)
{
if(yu==0) break;
if(yu>0) a[i]++,yu--;
}
}
}
for (int i = 1; i <= n; i++) b[i] += b[i - 1];