Money Transfers

There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.

Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.

There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.

Vasya doesn’t like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It’s guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks.

The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It’s guaranteed that the sum of all ai is equal to 0.

Output

Print the minimum number of operations required to change balance in each bank to zero.

Examples

Input
3
5 0 -5
Output
1

Input
4
-1 0 1 0
Output
2

Input
4
1 2 3 -6
Output
3

Note

In the first sample, Vasya may transfer 5 from the first bank to the third.

In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.

In the third sample, the following sequence provides the optimal answer:

1.transfer 1 from the first bank to the second bank;
2.transfer 3 from the second bank to the third;
3.transfer 6 from the third bank to the fourth.

题目大意:

有n个分布在圆圈上的银行,猪脚在某些银行的余额是负数,有些是正数。问至少需要将money移动多少次才能使每个银行的余额为0。(移动只能发生在相邻位置,由于是圆,1和n也算相邻)

解题思路:

根据题意可知最多的移动次数就是n-1,假设如果能够取出k个连续区间,使得每个区间内的和为0(由题意可知这个假设一定成立),那么移动的次数就是(n-1-(k-1))=n-k。那么k越大越好。这个连续区间的取法利用前缀和来实现,即从第一个数开始到最后一个数,每一项的前缀和为包括自身在内和前面的数的总和。出现次数最多的和的次数就是我们划分区间的数量。因为两项前缀和相同说明中间的区间和就是0。至于前面那一块可以和尾部那一块组成新的一个和为0的区间。这样就得到了我们要找的k个连续区间和为0的区间。

代码如下:

#include<iostream>
#include<cstdio>
#include<map>
#include<cmath>
using namespace std;
int a[100100];
int main()
{
  long long n;
  cin>>n;
  for(long long i=0;i<n;i++)cin>>a[i];
  map<long long,long long>k;//利用map的映射关系可以方便统计每种和出现的次数
  long long ma=0,sum=0;
  for(long long i=0;i<n;i++)
  {
    sum+=a[i];//前缀和
    k[sum]++;
    ma=max(ma,k[sum]);
  }
  cout<<n-ma<<endl;
  return 0;
}

这个题真是绞尽脑汁翻了很多博客又在纸上写写画画好久才恍然大悟。痛感智商欠费又本着对大佬给的解释太过简略的绝望,我把思路写的还算详细了。在最后BB几句权当吐槽了。

猜你喜欢

转载自blog.csdn.net/A7_RIPPER/article/details/81160409