题解:AT_ABC442_d

· · 题解

题目几乎是前缀和的模板题

题目传送门:link

solution

一看到题目我吓了一跳以为是树状数组模版题,但是当我看到交换的是相邻的两个数,哦哦那没事了(逃

直接使用前缀和即可。关键在于:交换相邻两个数时,只有一个位置的前缀和会发生变化,我们只需要单独更新它即可。具体地,当要交换 a_i 和 a_{i+1} 时,需要将 s_{i+1} 置为 s_i + a_i(此时的 a_i 是交换过的)。

求和的时候就用差分求出,比如要求 \displaystyle \sum_{l ~ \le ~ i ~ \le ~ r} a_i 可以由 s_r - s_{l-1} 求出。即可 O(1) 完成查询。

code

#include <bits/stdc++.h>
using namespace std;

int n, q, a[200005], s[200005], t;
int main()
{
    cin >> n >> q;
    for(int i = 0; i < n; i++)
    {
        cin >> a[i];
        s[i + 1] = s[i] + a[i];
    }
    while(q--)
    {
        cin >> t;
        if(t == 1)
        {
            int x; cin >> x;
            swap(a[x-1], a[x]);
            s[x] = s[x-1] + a[x-1];
        }
        else
        {
            int l, r; cin >> l >> r;
            cout << s[r] - s[l-1] << '\n';
        }
    }
}