Magic Squares

Description


You have n identical water tanks arranged in a circle on the ground. Each tank is connected with two neighbors by a pipe with a valve. All valves are initially closed, so water in each tank cannot move. But if all the valves are opened, water can flow freely among all the tanks. After some time, all the water levels will eventually equalize.
However, in many cases, only few valves need to be opened to equalize the water levels. For example, if the initial water levels are 10, 3, 5, 4, 1, 1, only 3 valves need to be opened (one valve between level 3 and level 5, another valve between level 1 and level 1, and the final one between level 1 and level 10).
Your task is to find the minimal number of valves to be opened, to equalize all water levels in each tank.


Input


The first line contains t (1<=t<=20), the number of test cases followed. Each test case begins with one integer n(3<=n<=200), followed by n non-negative integers not greater than 100, the initial water levels.


Output


For each test case, print the minimal number of valves to be opened.


Sample Input


3


6 10 3 5 4 1 1


4 4 4 3 3


8 2 1 1 2 2 1 1 6


Sample Output


3


2


5




题意:n个相同的水箱装有不同的量水 连成一个环,相邻两个tank之间有一个阀门,求最少打开几个开关,使得每个水箱的水量相同。

思路:n个开关,最坏的情况打开n-1个即可。至少可以有一个开关close。枚举一个开关关闭。然后求最少的连通方案。

直接上代码:

/*the code author is sunquan*/
/*2013-6-2 18:00*/
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

int main()
{
int t,n;
int a[200];
int total;//the sum of water
int ans;//answer
cin>>t;
while(t--)
{
cin>>n;
total=0;
for(int i=0;i<n;i++)
{
cin>>a[i];
total+=a[i];
}
ans=n-1;//the max number of valves to be opened
//enum the position of bump
for(int first=0;first<n;first++)
{
int sum,counter,open;
sum=counter=open=0;
for(int j=0; j<n;j++)
{
sum+=a[(first+j)%n];
counter++;
if(sum*n==total*counter)
counter=sum=0;
else
open++;
}
ans = ans<open?ans:open;
}
cout<<ans<<endl;
}
return 0;
}