树状数组TLE求助
查看原帖
树状数组TLE求助
1305692
xiangixuan楼主2025/1/19 20:09
#include<bits/stdc++.h>
#define N 500001
using namespace std;
int n, m, a[N], c[N];
int lowbit (int x) {return x&-x; }
void add_bit(int p, int v) {
	for (; p<=n; p+=lowbit(p)) c[p]+=v;
}
int query_bit(int p) {
	int v=0;
	for (; p; p-=lowbit(p)) v+=c[p];
	return v;
}
struct seg{
	int l, r, v;
	#define l(x) t[x].l
	#define r(x) t[x].r
	#define v(x) t[x].v
} t[4*N];
int ls(int p) {return p<<1; }
int rs(int p) {return (p<<1)+1; }
int mid(int p) {return l(p)+r(p)>>1; }
void build_seg(int p, int l, int r) {
	l(p)=l, r(p)=r;
	if (l==r) {v(p)=a[l]-a[l-1]; return; }
	build_seg(ls(p), l, mid(p));
	build_seg(rs(p), mid(p)+1, r);
	v(p)=__gcd(v(ls(p)), v(rs(p)));
}
void add_seg(int p, int x, int v) {
	if (l(p)==r(p)) {v(p)+=v; return; }
	if (x<=mid(p)) add_seg(ls(p), x, v);
	else add_seg(rs(p), x, v);
	v(p)=__gcd(v(ls(p)), v(rs(p)));
}
int query_seg(int p, int l, int r) {
	if (l<=l(p) && r>=r(p)) return v(p);
	int v=0;
	if (l<=mid(p)) v=__gcd(v, query_seg(ls(p), l, r));
	if (r>mid(p)) v=__gcd(v, query_seg(rs(p), l, r));
	return v;
}
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> n >> m;
	for (int i=1; i<=n; ++i) cin >> a[i];
	build_seg(1, 1, n);
	char opt; int x, y, z;
	while (m--) {
		cin >> opt;
		if (opt=='Q') {
			cin >> x >> y;
			cout << abs(__gcd(a[x]+query_bit(x), query_seg(1, x+1, y))) << '\n';
		} else {
			cin >> x >> y >> z;
			add_bit(x, z); if (y!=n) add_bit(y+1, -z);
			add_seg(1, x, z); if (y!=n) add_seg(1, y+1, -z);
		}
	}
	return 0;
}
2025/1/19 20:09
加载中...