1. 程式人生 > >【cf914D】Bash and a Tough Math Puzzle 線段樹

【cf914D】Bash and a Tough Math Puzzle 線段樹

題目大意

給出一個序列a,要求支援單點修改,以及詢問如果允許修改區間內的一個元素,區間gcd是否為x(可以理解為允許你暫時去掉區間一個元素,使區間gcd為x) 1 ≤ n ≤ 5*10^5 1 ≤ q ≤ 4·10^5

題解

一開始看題很萌比 後來看了題解發現自己是傻比系列 我們開一個線段樹 每個節點記錄當前區間的gcd,每次詢問只要查一下當前區間的gcd是否為x如果不是就繼續往下找,記錄一下需要修改幾次,只要找到需要修改兩個葉子節點就不要找了,返回NO。否則返回YES

程式碼

#include<iostream>
#include<algorithm>
#include
<cstdio>
#include<cstring> #include<cctype> #define N 500010 #define lson l,mid,st<<1 #define rson mid+1,r,st<<1|1 using namespace std; int tree[4*N],n,m; int gcd(int a,int b){while(b^=a^=b^=a%=b);return a;} void pushup(int x){tree[x]=gcd(tree[x<<1],tree[x<<1|1]
);} void build(int l,int r,int st) { if (l==r) {scanf("%d",&tree[st]);return;} int mid=(l+r)>>1; build(lson);build(rson); pushup(st); } void update(int x,int d,int l,int r,int st) { if (l==r) {tree[st]=d;return;} int mid=(l+r)>>1; if (x<=mid) update(x,d,lson); else update(
x,d,rson); pushup(st); } int query(int L,int R,int x,int l,int r,int st) { if (l==r) return 1; int mid=(l+r)>>1,ret=0; if (L<=mid&&tree[st<<1]%x!=0) ret+=query(L,R,x,lson); if (R>mid&&tree[st<<1|1]%x!=0&&ret<=1) ret+=query(L,R,x,rson); return ret; } int main() { scanf("%d",&n); build(1,n,1); scanf("%d",&m); for (int i=1;i<=m;i++) { int op,L,R,x; scanf("%d",&op); if (op==2) scanf("%d%d",&L,&R),update(L,R,1,n,1); else scanf("%d%d%d",&L,&R,&x),query(L,R,x,1,n,1)<=1?printf("YES\n"):printf("NO\n"); } return 0; }