• bzoj 1045: [HAOI2008] 糖果传递


    题目链接

    1045: [HAOI2008] 糖果传递

    Time Limit: 10 Sec  Memory Limit: 162 MB
    Submit: 3065  Solved: 1384
    [Submit][Status][Discuss]

    Description

    有n个小朋友坐成一圈,每人有ai个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为1。

    Input

    小朋友个数n 下面n行 ai

    Output

    求使所有人获得均等糖果的最小代价。

    Sample Input

    4
    1
    2
    5
    4

    Sample Output

    4

    HINT

    100% n<=987654321

    给的这个数据是搞笑的吧...其实只有1e6。
    我们令a1, a2...为每个位置初始值,ave为平均值。 x1表示a1 给an的数量, x2表示a2给a1的数量, ......。我们所求即为|x1|+|x2|+.....|xn| 那么显然
    a1-x1+x2 = ave   ->   x2 = ave+x1-a1 = x1-c1(c1 = a1-ave)
    a2-x2+x3 = ave ->   x3 = ave+x2-a2 = 2*ave+x1-a1-a2 = x1-c2(c2 = 2*ave+a1+a2) .
    ...
    an-x(n-1)+x1 = ave.
    观察可知ci是一个前缀和。
    |x1|+|x2|+....|xn|可以变为|x1|+|x1-c1|+|x1-c2|+...|x1-cn|, 可以理解为数轴上n个点到c1的距离的和, 那么显然应该找中位数。
    #include <iostream>
    #include <vector>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    #include <map>
    #include <set>
    #include <string>
    #include <queue>
    #include <stack>
    #include <bitset>
    using namespace std;
    #define pb(x) push_back(x)
    #define ll long long
    #define mk(x, y) make_pair(x, y)
    #define lson l, m, rt<<1
    #define mem(a) memset(a, 0, sizeof(a))
    #define rson m+1, r, rt<<1|1
    #define mem1(a) memset(a, -1, sizeof(a))
    #define mem2(a) memset(a, 0x3f, sizeof(a))
    #define rep(i, n, a) for(int i = a; i<n; i++)
    #define fi first
    #define se second
    typedef pair<int, int> pll;
    const double PI = acos(-1.0);
    const double eps = 1e-8;
    const int mod = 1e9+7;
    const int inf = 1061109567;
    const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
    int a[1000005], pre[1000005];
    int main()
    {
        ll n, sum = 0;
        cin>>n;
        for(int i = 1; i<=n; i++) {
            scanf("%d", &a[i]);
            sum+=a[i];
        }
        sum/=n;
        for(int i = 2; i<=n; i++) {
            pre[i] = pre[i-1]+a[i]-sum;
        }
        sort(pre+1, pre+1+n);
        ll ans = 0;
        int mid = pre[(n>>1)+1];
        for(int i = 1; i<=n; i++) {
            ans += abs(pre[i]-mid);
        }
        cout<<ans<<endl;
        return 0;
    }
  • 相关阅读:
    淘宝网的质量属性分析
    软件架构师如何工作
    软件需求管理用例方法三
    软件需求管理用例方法二
    git使用教程
    javascript获取鼠标点击位置的坐标兼容写法
    ES5中数组的方法
    JavaScript数组常用方法
    JavaScript中for..in循环陷阱介绍
    【转】web前端开发必知必会(面试、笔试可能用到)
  • 原文地址:https://www.cnblogs.com/yohaha/p/5224943.html
Copyright © 2020-2023  润新知