题解:AT_abc442_d [ABC442D] Swap and Range Sum

· · 题解

A 数组求前缀和,对于操作二,正常查询,直接输出 sum_r - sum_{l - 1};对于操作一,显然 sum_{x - 1}sum_{x + 1} 都不会受影响,只有 sum_{x} 会受影响,所以我们就修改 sum_x 然后再交换 A_xA_{x + 1} 就可以了。

sum_x$ 的修改公式:$sum_{x}^{'} = sum_{x} + a_{x + 1} - a_{x}

AC 代码:

#include"bits/stdc++.h"
const int N = 2e5 + 5;
int a[N],sum[N];
int main(){
    std::cin.tie(0)->sync_with_stdio(0);
    int n,q;std::cin >> n >> q;
    for (int i = 1;i <= n;i++) std::cin >> a[i],sum[i] = sum[i - 1] + a[i];
    while (q--){
        int op,x,l,r;std::cin >> op;
        if (op == 1){
            std::cin >> x;
            sum[x] += a[x + 1] - a[x];
            std::swap(a[x],a[x + 1]);
        }
        else{
            std::cin >> l >> r;
            std::cout << sum[r] - sum[l - 1] << '\n';
        }
    }
    return 0;
}