跳到正文

题解

题解:AT_abc442_d [ABC442D] Swap and Range Sum

wjy7777约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年1月24日
收录
2026年2月10日
更新
2026年11月16日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

感觉 C 严格大于 D。

题目传送门

思路

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

  • 对于操作一:把 AxA_{x} 与 Ax+1A_{x+1} 的值记录下来,然后把这两个位置的数清零,分别加上 Ax+1A_{x+1} 与 AxA_{x} 即可。

  • 对于操作二:树状数组前缀和。

代码

C++
#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;
}
原文