zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    ubuntu多版本java并切换环境
    ssh 免密登陆
    linux系统的文件和目录
    docker-compose简介及使用
    vue3.0 + html2canvas 一键截图
    vue3.0 无法获取对象值
    算法——回溯算法 (Back Tracking) (转)
    VMware——CentOS-64 7——桥接模式无法连接网络的问题
    groovy 字符串和闭包
    https://blog.didispace.com/
  • 原文地址:https://www.cnblogs.com/yohaha/p/5224943.html
Copyright © 2011-2022 走看看