SCU-1005: Move cards

1005: Move cards

Submit your solution     Discuss this problem     Best solutions

The Problem

There are N piles of cards, and these piles are numbered as 1,2,...,N respectively. Each pile has some cards, while the total of all cards must be a multiple of N. The player can take some cards from one pile and then put them on another pile as one step.

The follow is the rules: the cards on the pile numbered 1 can only be moved to the pile 2; the cards on the pile N can only be moved to the pile N-1; the cards on other piles, numbered from 2 to N-1, can be moved to either their left pile or right one.

Now the player should move these cards to make the card numbers of each pile equal by minimum steps.

For example: there are 4 piles, and the card numbers of each pile are 9 8 17 6 respectively. So it needs 3 steps to achieve the goal at least.

The Input

The input file consists of one or more test cases. The first line of input is the number of cases. Each case contains 2 lines: the first line of each case contains the only number N indicating the number of piles, and the second line contains a group of integers separated by space, indicating the card numbers of each pile respectively.

The Output

The minimum steps to make all piles' card numbers equal.

 

Sample input

1
4
9 8 17 6

Sample output

3

 

解题思路:

要将他们变成相同的数我们就要做到,将他们变成平均数。所以计算出他们的平均数然后,依次和平均数进行比较,并且从后边的数上加上或减去,等于平均数不用记录步数。

 

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int map[1000000],n;
 
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		int i,j;
		int ss=0;
		for(i=0;i<n;i++)
		{
			scanf("%d",&map[i]);
			ss+=map[i];
		}
		ss=ss/n;
		int ans=0;
		for(i=0;i<n-1;i++)
		{
			if(map[i]>ss)
			{
				map[i+1]+=map[i]-ss;
				map[i]=ss;
				ans++;
			}
			if(map[i]<ss)
			{
				map[i+1]-=ss-map[i];
				map[i]=ss;
				ans++;
			}
		}
		printf("%d\n",ans);
	}	
	return 0;
}
 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值