D. Bash and a Tough Math Puzzle(思维+线段树+剪枝)

https://codeforces.com/problemset/problem/914/D


思路:

考虑如何快速判断gcd[l,r]%x是否可以修改一个数得出。如果答案满足,那么其必然是有一个不是x的倍数,或者都是x的倍数。因为最多只能将一个不是x的倍数改成x。或者将都是x的倍数其中一个改成最小的x就是了。

如果这样其实还是暴力了。如果一段区间的gcd是x的倍数,说明这段区间就可以return了。如果不是,看这段区间的左儿子和右儿子,如果两个%x!=0,那么至少要cnt=2;不然就搜其中一个儿子,

那么需要递归到叶子节点看有几个不是x的倍数,cnt++。

同时dfs的过程中设一个全局的flag反应当前是否已经有cnt>=2,有的话直接return完就好了。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
struct Tree{
   LL l,r,gcd;
}tree[maxn*4];
void push_up(LL p){
     tree[p].gcd=__gcd(tree[p*2].gcd,tree[p*2+1].gcd);
}
void build(LL p,LL l,LL r){
     tree[p].l=l;tree[p].r=r;tree[p].gcd=0;
     if(l==r){LL x;cin>>x;tree[p].gcd=x;return;}
     LL mid=(tree[p].l+tree[p].r)>>1;
     build(p*2,l,mid);build(p*2+1,mid+1,r);
     push_up(p);
}
void modify(LL p,LL l,LL r,LL d){
     if(l<=tree[p].l&&r>=tree[p].r){
        tree[p].gcd=d;
        return;
     }
     LL mid=(tree[p].l+tree[p].r)>>1;
     if(l<=mid) modify(p*2,l,r,d);
     if(r>mid) modify(p*2+1,l,r,d);
     push_up(p);
}
void query(LL p,LL l,LL r,LL x,LL& cnt){
     if(cnt>=2) return;
     if(tree[p].l==tree[p].r){
        if(tree[p].gcd%x){cnt++;return;}
        return;
     }
     if(l<=tree[p].l&&r>=tree[p].r){///需要递归到叶子节点
          if(tree[p].gcd%x==0) return;
          if(tree[p*2].gcd%x!=0&&tree[p*2+1].gcd%x!=0) {
                cnt+=2;
                return;
          }
          if(tree[p*2].gcd%x!=0) query(p*2,l,r,x,cnt);
          if(tree[p*2+1].gcd%x!=0) query(p*2+1,l,r,x,cnt);
          return;
     }
     LL mid=(tree[p].l+tree[p].r)>>1;
     if(l<=mid) query(p*2,l,r,x,cnt);
     if(r>mid)  query(p*2+1,l,r,x,cnt);
     return;
}
int main(void){
   cin.tie(0);std::ios::sync_with_stdio(false);
   LL n;cin>>n;
   build(1,1,n);
   LL q;cin>>q;
   while(q--){
      LL op;cin>>op;
      if(op==1){
         LL l,r,x;cin>>l>>r>>x;
         LL cnt=0;
         query(1,l,r,x,cnt);
         if(cnt>=2){
            cout<<"NO"<<"\n";
         }
         else if(cnt==0||cnt==1){
            cout<<"YES"<<"\n";
         }
      }
      else if(op==2){
         LL i,y;cin>>i>>y;
         modify(1,i,i,y);
      }
   }
   return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值