AT_abc423_e 题解

· · 题解

嗯。所以我赛时干什么去了这题都没推出来。

很简单的推式子题。

题意我就不多说了啊。

首先考虑一个位置 i 在区间为 [l,r] 的情况下带来的贡献是多少。容易得出算式 (i-l+1) \times (r-i+1) \times a_i。你问我怎么得出来的?很简单,前两项算 a_i 总共被计算了多少次(左端点数量乘上右端点数量),然后再乘上具体数值 a_i 即可。毫无难度。

但是这个东西好混乱哦,我们把式子拆一下吧。

(i-l+1) \times (r-i+1) \times a_i = i \times r \times a_i - i^2 \times a_i + i \times a_i - l \times r \times a_i + l \times i \times a_i - l \times a_i + r \times a_i - i \times a_i + a_i = (l+r) \times (a_i \times i) - 1 \times (i^2 \times a_i) - (l \times r + l - r - 1) \times (a_i)

提取后发现只有三项,a_i \times i,i^2 \times a_i,以及 a_i。那么分别对这三项维护前缀和即可。算的时候乘一下系数即可。

记得开 long long!千万要记得给 i 开 long long。我因为这玩意儿调了一晚上。

#include<bits/stdc++.h>
#define LL long long
#define UInt unsigned int
#define ULL unsigned long long
#define LD long double
#define pii pair<int,int>
#define pLL pair<LL,LL>
#define fr first
#define se second
#define pb push_back
using namespace std;
const int N = 3e5+5;
LL n,Q,a[N],s[N],t[N],p[N];
LL read(){
    LL su=0,pp=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')pp=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){su=su*10+ch-'0';ch=getchar();}
    return su*pp;
}
int main(){
    n=read(),Q=read();
    for(LL i=1;i<=n;i++){
        a[i]=read();
        s[i]=s[i-1]+a[i];
        t[i]=t[i-1]+i*i*a[i];
        p[i]=p[i-1]+a[i]*i;
    }
    while(Q--){
        LL l=read(),r=read();
        LL Ans
        =(p[r]-p[l-1])*(l+r)
        -(t[r]-t[l-1])
        -(s[r]-s[l-1])*(l*r+l-r-1);
        cout<<Ans<<"\n";
    }
    return 0;
}

如果本篇题解对你有帮助的话,还麻烦你点一个小小的赞,真是太感谢啦!