Cyclic balance

265 篇文章 1 订阅

For an array a[n], and sum(a[i]|i=0..n-1) mod n == 0. There is an operation, which can set a[i] to a[i]-1, meanwhile, a[i-1] to a[i-1]+1 or a[i+1] to a[i+1]+1. 

Problem 1: How many operations do you need to make every a[i] equal to the average value?

Problem 2: If the array is cyclic, what's the result?

----------------------------------------------------------------------

For problem 1, 

We could define c[i] as Sum[a[k] | k = 0..i] - avg*(i + 1), so 

res = abs(c[0]) + abs(c[1]) +...+abs(c[n-1])


For problem 2,

I could only find the O(n^2) solution, but a friend give me a O(n) Solution, like this:

\

So, t[i] stands for the number transferred from a[i] to a[i-1], so


t[1]-t[0] = avg - a[0]

t[2]-t[1] = avg - a[1]

....

t[n-1]-t[n-2] = avg - a[n-2]

So t[i] = avg*i - Sum(a[0..i-1])+t[0] = t[0] + c[i-1]

What we need to do is 

Minimize {abs(t[0])+abs(t[1])+....abs(t[n-1])} = Minimize{abs(t[0])+abs(t[0]+c[0])+...abs(t[0]+c[n-2])}

We could get every c in advance, O(n)


So the problem is what is the value of t[0] to make the sum of abs minimization?







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值