UPC——Contest2971 - 2021秋组队训练赛第十五场

C题

Crisis at the Wedding
算是思维题吧,注意代价是累加的,用前缀和表示

// #pragma GCC optimize(3, "Ofast", "inline")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
const int N = 1e5 + 10;
const int M = 2e6 + 1000;
const int inf = 1e9;
const int mod = 1000000007;
const int pi = acos(-1);
#define IOS                  \
    ios::sync_with_stdio(0); \
    cin.tie(0);              \
    cout.tie(0);
ll n, sum, res;
ll a[N], s1[N], b[N], s2[N];
int main()
{
    // IOS;
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++)
    {
        scanf("%lld", &a[i]);
        b[n - i + 1] = a[i];
        sum += a[i];
    }
    ll ave = sum / n, mi = inf;
    sum = 0;
    for (int i = 1; i <= n; i++)
    {
        a[i] -= ave;
        s1[i] = s1[i - 1] + a[i]; //1开始的,i到i+1的代价
        sum += s1[i];             //sum是从1开始的总代价
        mi = min(mi, s1[i]);
    }
    res = sum - mi * n;
    // printf("%lld**%lld**%lld\n", res,sum,mi);
    mi = inf, sum = 0;
    // memset(s, 0, sizeof(s));
    for (int i = 1; i <= n; i++)
    {
        b[i] -= ave;
        s2[i] = s2[i - 1] + b[i]; //1开始的,i到i+1的代价
        sum += s2[i];             //sum是从1开始的总代价
        mi = min(mi, s2[i]);
    }
    printf("%lld\n", min(res, sum - mi * n));
    return 0;
}
上一篇:Harmonic Number (II)(找规律,思维)


下一篇:CF903G-Yet Another Maxflow Problem【线段树,最大流】