1098 均分纸牌

题目
题目描述 Description

有 N 堆纸牌,编号分别为 1,2,…, N。每堆上有若干张,但纸牌总数必为 N 的倍数。可以在任一堆上取若于张纸牌,然后移动。
  移牌规则为:在编号为 1 堆上取的纸牌,只能移到编号为 2 的堆上;在编号为 N 的堆上取的纸牌,只能移到编号为 N-1 的堆上;其他堆上取的纸牌,可以移到相邻左边或右边的堆上。
  现在要求找出一种移动方法,用最少的移动次数使每堆上纸牌数都一样多。

  例如 N=4,4 堆纸牌数分别为:
  ① 9 ② 8 ③ 17 ④ 6
  移动3次可达到目的:
  从 ③ 取 4 张牌放到 ④ (9 8 13 10) -> 从 ③ 取 3 张牌放到 ②(9 11 10 10)-> 从 ② 取 1 张牌放到①(10 10 10 10)。

输入描述 Input Description

第一行N(N 堆纸牌,1 <= N <= 100)
第二行A1 A2 … An (N 堆纸牌,每堆纸牌初始数,l<= Ai <=10000)

输出描述 Output Description

输出至屏幕。格式为:
所有堆均达到相等时的最少移动次数。‘

样例输入 Sample Input

4
9 8 17 6

样例输出 Sample Output

3

分析

这是一个贪心问题(我并不这么觉得,感觉只是找找规律而已),过程挺难想的,大致是用x记录前i堆距离全变成平均值还差几张纸牌,只要此时的x不等于平均值(即前i堆还不足以使每堆都相等)记录数量的y就加1

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<ctime>
#include<vector>
#include<set>
#include<map>
#include<stack>
using namespace std;
int a[2000100];
int main()
{     int n,m,i,j,k,p=0,x=0,y=0;
      cin>>n;
      for(i=1;i<=n;i++){
          cin>>a[i];
          p+=a[i];
      }
      p/=n;
      for(i=1;i<=n;i++){
          k=x;
          x+=(a[i]-p);
          if(x!=0)y++;
      }
      cout<<y<<endl;
      return 0;
}

原文地址:https://www.cnblogs.com/yzxverygood/p/7726292.html