CH4302-Interval GCD(线段树+树状数组+GCD)

版权声明:蒟蒻的博文,dalao转载标明出处就好吖 https://blog.csdn.net/jokingcoder/article/details/88250997

原题地址

题意

维护两个操作

  • 区间加
  • 区间GCD

Soluiton

这里有一个很巧妙的方法——更相减损术

就是数论里的加减法对GCD封闭

也就是 g c d ( a 1 , a 2 , . . . , a n ) = g c d ( a 1 , a 2 a 1 , a 3 a 2 , . . . , a n a n 1 ) gcd(a_1, a_2, ..., a_n)=gcd(a_1, a_2-a_1, a_3-a_2, ..., a_n-a_{n-1})

于是就可以把区间修改转换成了两个端点的修改(只需要对原数组做一次查分即可)

对于维护 g c d ( l r ) gcd(l \to r) ,可以通过线段树求出 g c d ( l + 1 r ) gcd(l + 1\to r) ,而 a [ l ] a[l] 需要再通过一棵线段树或树状数组来维护

坑——题目最上方说N<=5e5,下方是2e5,要以大的为准,同时需要开long long

Code

#include <cstdio>
#define N 500010

using namespace std;
typedef long long LL;
LL sub[N << 2], a[N], b[N], n, tree[N];

inline LL gcdd(LL x, LL y) { if (y == 0) return x; return gcdd(y, x % y); }
inline LL gcd(LL x, LL y) { if (x < 0) x = -x; if (y < 0) y = -y; return gcdd(x, y); }
inline void pushup(LL rt) { sub[rt] = gcd(sub[rt << 1], sub[rt << 1 | 1]); }
inline LL lowbit(LL x) { return x & -x; }
inline void update(LL l, LL x) { while (l <= n) { tree[l] += x; l += lowbit(l); } }
inline LL query_tree(LL x) { LL ans = 0; while (x > 0) { ans += tree[x]; x -= lowbit(x); } return ans; }

inline void build(LL l, LL r, LL rt) {
	if (l == r) { sub[rt] = b[l]; return; } LL mid = l + r >> 1;
	build(l, mid, rt << 1); build(mid + 1, r, rt << 1 | 1);
	pushup(rt);
}

inline void modify(LL l, LL r, LL P, LL rt, LL v) {
	if (P < l || P > r) return;
	if (l == r) { sub[rt] += v; return; } LL mid = l + r >> 1;
	modify(l, mid , P, rt << 1, v); modify(mid + 1, r, P, rt << 1 | 1, v);
	pushup(rt);
}

inline LL query(LL l, LL r, LL L, LL R, LL rt) {
	if (r < L || l > R) return 0; if (L <= l && r <= R) return sub[rt];
	LL mid = l + r >> 1, ls = query(l, mid, L, R, rt << 1), rs = query(mid + 1, r, L, R, rt << 1 | 1);
//	prLLf("%d %d\n", ls, rs);
	return gcd(ls, rs);
}

int main() {
	LL m, l, r, num;
	scanf("%lld%lld", &n, &m);
	for (LL i = 1; i <= n; ++i) scanf("%lld", &a[i]);
	for (LL i = n; i >= 1; --i) {
		b[i] = a[i] - a[i - 1];
		update(i, b[i]);
	}
	build(1, n, 1);
	while (m--) {
		char ch = getchar();
		while (ch != 'C' && ch != 'Q') ch = getchar();
		if (ch == 'C') scanf("%lld%lld%lld", &l, &r, &num), update(l, num), update(r + 1, -num), modify(1, n, l, 1, num), modify(1, n, r + 1, 1, -num);
		if (ch == 'Q') scanf("%lld%lld", &l, &r), printf("%lld\n", gcd(query_tree(l), query(1, n, l + 1, r, 1)));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/jokingcoder/article/details/88250997