【hihocoder 1499】A Box of Coins

【题目链接】:http://hihocoder.com/problemset/problem/1499

【题意】

【题解】

贪心,模拟;
从左往右对于每一列;
如果上下两个格子;

有一个格子超过了所需;
另外一个格子小于所需;
则把超过了的格子转移一些到小于的那个,让上下两个互补;
然后把剩下的往右传(肯定是要往右传的);

如果两个格子都超过了所需;
则把两个格子多余的硬币都往右传.

如果两个格子都小于所需;
则两个格子都从右边借一些


【Number Of WA

1(输入是一列一列地输入的…)

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 100500;

int n;
LL a[3][N],sum,goal,ans = 0;

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    cin >> n;
    rep1(i,1,n)
    {
        cin >> a[1][i] >> a[2][i];
        sum+=a[1][i],sum+=a[2][i];
    }
    goal = sum/(2*n);
    rep1(j,1,n)
    {
        if (a[1][j]>=goal && a[2][j]>=goal)
        {
            ans+=a[1][j]-goal,ans+=a[2][j]-goal;
            a[1][j+1]+=a[1][j]-goal;
            a[2][j+1]+=a[2][j]-goal;
            continue;
        }
        if (a[1][j]>=goal && a[2][j]<goal)
        {
            LL need = goal-a[2][j],have = a[1][j]-goal;
            if (have>=need)
            {
                ans+=have;
                a[1][j+1]+=have-need;
            }
            else
            {
                ans+=have;
                a[2][j]+=have;
                a[2][j+1]-=(goal-a[2][j]);
                ans+=(goal-a[2][j]);
            }
            continue;
        }
        if (a[1][j]<goal && a[2][j]>=goal)
        {
            LL need = goal-a[1][j],have = a[2][j]-goal;
            if (have>=need)
            {
                ans+=have;
                a[2][j+1]+=have-need;
            }
            else
            {
                ans+=have;
                a[1][j]+=have;
                a[1][j+1]-=(goal-a[1][j]);
                ans+=goal-a[1][j];
            }
            continue;
        }
        if (a[1][j]<goal && a[2][j] < goal)
        {
            ans+=goal-a[1][j],ans+=goal-a[2][j];
            a[1][j+1]-=(goal-a[1][j]),a[2][j+1]-=(goal-a[2][j]);
            continue;
        }
    }
    cout << ans << endl;
    return 0;
}
posted @ 2017-10-04 18:44  AWCXV  阅读(133)  评论(0编辑  收藏  举报