Magic Squares

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值