题解:CF2239B Decidophobia

· · 题解

看到是个环我们直接断环成链。

我们考虑对于第 i 个人送礼物,那么我们会收到 2d \cdot a_i 的贡献,同时对于其两侧的共 2d 个人都会减去 a_j 的贡献,每个人的计算都是独立的,那么只要 2d \cdot a_i > \sum a_j 也是就正贡献大于负贡献,我们就可以给他送礼物。

对于一侧的 \sum a_j 只要用前缀和优化即可,时间复杂度为 O(n) 的。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define db double
#define ll long long
#define int ll
#define endl "\n"
using namespace std;
const int N = 6e5 + 10;//断环成链开3倍数组
inline int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')
            f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
        x = x*10+ch-'0',ch = getchar();
    return x * f;
}
int a[N],sum[N];
signed main()
{
    int t = read();
    while(t--)
    {
        int n = read(),d = read();
        for(int i = 1;i<=n;++i)
        {
            a[i] = read();
            a[i+n] = a[i];
            a[i+n+n] = a[i];
        }
        sum[0] = 0;
        for(int i = 1;i<=3*n;++i)
            sum[i] = sum[i-1]+a[i];
        int ans = 0;
        for(int i = n+1;i<=2*n;++i)
        {
            int l = sum[i-1]-sum[i-1-d];
            int r = sum[i+d]-sum[i];
            if(2*d*a[i] > l+r)
                ans += 2*d*a[i]-l-r;
        }
        cout<<ans<<endl;
    }
    return 0;
}