zoukankan      html  css  js  c++  java
  • [BZOJ1045]糖果传递

    Problem

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

    Solution

    我们假设第i为同学给了第i+1为同学Xi个糖果(n的后一位为1)
    所以ans = X1 + X2 + X3 + ······ + Xn
    我们可以列出方程:A1+Xn-X1=average,A2+X1-X2=average,······,An+Xn-1-Xn=average
    所以X1=A1+Xn-average,X2=A2+X1-average=X1-C1,······,Xn=An+Xn-1-average=X1-Cn-1
    所以我们可以计算出C数组,然后问题转化为求|X1|+|X1-C1|+|X1-C2|+······+|X1-Cn-1|
    由初中数学的,此时最小值为X1位于在最中间的两个点中间任意一点上都可以取到最小值
    所以只需要求出中位数
    详情参见:http://hzwer.com/2656.html

    Notice

    想到思路就很简单了

    Code

    #include<cmath>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    #define sqz main
    #define ll long long
    #define reg register int
    #define rep(i, a, b) for (reg i = a; i <= b; i++)
    #define per(i, a, b) for (reg i = a; i >= b; i--)
    #define travel(i, u) for (reg i = head[u]; i; i = edge[i].next)
    const int INF = 1e9, N = 1000000;
    const double eps = 1e-6, phi = acos(-1.0);
    ll mod(ll a, ll b) {if (a >= b || a < 0) a %= b; if (a < 0) a += b; return a;}
    ll read(){ ll x = 0; int zf = 1; char ch; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
    if (ch == '-') zf = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;}
    void write(ll y) { if (y < 0) putchar('-'), y = -y; if (y > 9) write(y / 10); putchar(y % 10 + '0');}
    ll ans;
    ll X[N + 5];
    int sqz()
    {
    	int n = read();
    	rep(i, 1, n)
    	{
    		int T = read();
    		X[i] = X[i - 1] + T;
    	}
    	rep(i, 2, n) X[i] -= X[n] / n * (i - 1);
    	sort(X + 1, X + n + 1);
    	rep(i, 1, n) ans += abs(X[i] - X[(n + 1) / 2]);
    	printf("%lld
    ", ans);
    }
    
  • 相关阅读:
    Integer to Roman leetcode java
    Reverse Integer leetcode java
    Binary Tree Maximum Path Sum leetcode java
    公司来了一个奇葩需求pppoe client+server+EOIP+vlan
    魔兽数据库-自然
    windows默认dns解析走ipv4而不走ipv6
    ROS支持BCP桥接(基于PPP隧道)
    几款比较好用的电动理发器推荐
    centos 拨号pptp在拨号成功和拨号失败的时候脚本处理!!!非常重要
    ros routeros 脚本命令script
  • 原文地址:https://www.cnblogs.com/WizardCowboy/p/7737319.html
Copyright © 2011-2022 走看看