题解:P13095 [FJCPC 2025] 炒股高手

· · 题解

思路分析

简单观察发现:最大收益来自所有递增区间的差值总和。

为此,可预处理一个前缀和数组,存储从第 2 天到当天的差值。

然后就方便多了,这样就可以对于每个查询区间 [s,t],只需计算前缀和数组在 t 与 s 的差值再加 k,就是答案了。

代码实现

#include<bits/stdc++.h>
#define please return
#define AC 0
#define rep(i, a, b) for(long long i = a; i <= b; i++)
#define repr(i, a, b) for(long long i = a; i >= b; i--)
using namespace std;

typedef long long LL;
int main() {
    LL n, m; scanf("%lld%lld", &n, &m);
    vector<LL> a(n + 10);
    rep(i, 1, n) scanf("%lld", &a[i]);
    // for(LL &x : a) scanf("%lld", &x);
    // LL pre[m + 10];
    // memset(pre, 0, sizeof(pre));
    vector<LL> pre(n + 10, 0);
    // rep(i, 1, n - 1) pre[i] = pre[i - 1] + max(0, a[i] - a[i - 1]);
    rep(i, 2, n) pre[i] = pre[i - 1] + max(0LL, a[i] - a[i - 1]);
    LL k; scanf("%lld", &k);
    while(m--) {
        LL s, t; scanf("%lld%lld", &s, &t);
        // s--; t--;
        LL cun = pre[t] - pre[s];
        printf("%lld\n", k + cun);
    }
    please AC; 
}