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


你可能感兴趣的:(Math,scu)