【贪心】均分纸牌

【贪心】均分纸牌

题目描述

有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)。

输入

输入文件中包括两行数据。
第一行为N堆纸牌数(1<=N<=100)。
第二行为N堆纸牌中每堆纸牌初始数A1,A2,…,An(l<=Ai<=10000)。

输出

输出文件中仅一行,即所有堆均达到相等时的最少移动次数。

样例输入

4
9 8 17 6

样例输出

3
分析:因为每张纸牌只能移到相邻纸牌,且1只能移到2,n只能移到n-1,所以每次把最左边的纸牌变成目标状态,并转移成减少一张牌的状态;
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <ext/rope>
#define rep(i,m,n) for(i=m;i<=n;i++)
#define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++)
#define vi vector<int>
#define pii pair<int,int>
#define mod 1000000007
#define inf 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define pi acos(-1.0)
const int maxn=1e3+10;
const int dis[][2]={0,1,-1,0,0,-1,1,0};
using namespace std;
using namespace __gnu_cxx;
ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);}
ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;}
int n,m,a[maxn],ans,sum,now;
int main()
{
    int i,j,k,t;
    scanf("%d",&n);
    rep(i,0,n-1)scanf("%d",&a[i]),sum+=a[i];
    sum/=n;
    rep(i,0,n-1)
    {
        if(a[i]!=sum)a[i+1]+=a[i]-sum,ans++;
    }
    printf("%d
",ans);
    //system("pause");
    return 0;
}

原文地址:https://www.cnblogs.com/dyzll/p/5696988.html