题解:AT_abc442_d [ABC442D] Swap and Range Sum

· · 题解

感觉 C 严格大于 D。

题目传送门

思路

注意到有单点修改与区间查询,所以本题使用树状数组来解决。

代码

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/priority_queue.hpp>
#include <ext/pb_ds/hash_policy.hpp>
using namespace std;
#define int long long 
#define lb long double
#define fir first
#define sec second
#define mk make_pair
#define pii pair<int,int>
#define pb push_back
#define pf push_front
#define pq priority_queue
#define max(a,b) (a>b ? a : b )
#define min(a,b) (a<b ? a : b )
#define endl '\n'
#define lowbit(x) (x & (-x))
#define ccmap __gnu_pbds::cc_hash_table  //<Key,Value> xxx; //à-á′·¨
#define gpmap __gnu_pbds::gp_hash_table  //<Key,Value> xxx£? //ì??°·¨£¨???ì£?
void read(int &x) {
    bool neg=false;
    x=0;
    char ch=0;
    while (ch<'0' || ch>'9') {
        if (ch=='-') neg=true;
        ch=getchar();
    }
    if (neg) {
        while (ch>='0' && ch<='9') {
            x=x*10+('0'-ch);
            ch=getchar();
        }
    } else {
        while (ch>='0' && ch<='9') {
            x=x*10+(ch-'0');
            ch=getchar();
        }
    }
}
void write(int x) {
    bool neg=false;
    if (x<0) {
        neg=true;
        putchar('-');
    }
    static int sta[40];
    int top=0;
    do {
        sta[top++]=x%10;
        x/=10;
    } while (x);
    if (neg) {
        while (top) putchar('0'-sta[--top]);
    } else {
        while (top) putchar('0'+sta[--top]);
    }
    return ;
}

/*-------------------------------------------------------------------------*/
int n,T;
int a;
int op,x,y;
int t[200009];
void udt(int x,int y){
    while (x<=n){
        t[x]+=y;
        x+=lowbit(x);
    } 
} 
int ask(int x){
    int s=0;
    while (x){
        s+=t[x];
        x-=lowbit(x);
    }
    return s;
}
signed main() {
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);
    cin>>n>>T;
    for (int i=1;i<=n;i++){
        cin>>a;
        udt(i,a);
    }
    while (T--){
        cin>>op;
        if (op==1){
            cin>>x;
            int u=ask(x)-ask(x-1),v=ask(x+1)-ask(x);
            udt(x,-u);
            udt(x+1,-v);
            udt(x,v);
            udt(x+1,u);
        }
        else {
            cin>>x>>y;
            cout<<ask(y)-ask(x-1)<<endl;
        }
    }
    return 0;
}