ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

B - Bash and a Tough Math Puzzle CodeForces - 914D (线段树的巧妙应用)

2020-04-04 20:52:31  阅读:225  来源: 互联网

标签:Tough gcd int Puzzle tree CodeForces mid return root


题目大意:当输入2时,将p处的点的值修改为x,

     当输入1时,判断区间[L,R]的gcd是否几乎正确,几乎正确的定义是最多修改一个数,使得区间[L,R]的gcd为x。

题解:用线段树维护一个gcd数组,在查询的时候,线段树的查询本质就是不停的分块,这时我们可以添加一些剪纸,比如说,对一个根节点root,如果说他的左儿子的值为tree[root*2],如果他他是x的倍数,那就没必要往下分了。如果不是的话,就往下分,直到找到了某一个点,我们可以记录一下,如果说点的个数大于等于2直接可以退出了。(太秒了,我刚开始也是这样想的,当时觉得如果查每个值的话,复杂度不就是o(n)了?,如果不加剪枝的话,确实是o(n),如果加了剪枝,还是log,秒~)

code:

  

#include<bits/stdc++.h>
using namespace std;
const int N=5E5+7;
int arr[N];
int tree[N+N+N]; 
int n;
int cnt;
int gcd(int a,int b){
    return b? gcd(b,a%b):a;
}
void push(int root){
    tree[root]=gcd(tree[root*2],tree[root*2+1]);
}
void build(int root,int l,int r){
    if(l>r) return ;
    if(l==r){
        scanf("%d",&tree[root]);
        return ;
    }
    int mid=(l+r)>>1;
    build(2*root,l,mid);
    build(2*root+1,mid+1,r);
    push(root); 
}
void update(int root,int l,int r,int pos,int x){
    if(l>pos||r<pos||l>r) return ;
    if(l==r){
        if(l==pos) tree[root]=x;
        return ;
    }
    int mid=(l+r)>>1;
    update(root*2,l,mid,pos,x);
    update(root*2+1,mid+1,r,pos,x);
    push(root);
}
void query(int root,int l,int r,int xl,int xr,int x){ 
    if(cnt==2) return ;
    if(l>r||xr<l||r<xl) return ;
    if(l==r){
        if(tree[root]%x) cnt++;
        return ;
    }
    int mid=(l+r)>>1;
    if(tree[root*2]%x) query(root*2,l,mid,xl,xr,x);
    if(tree[root*2+1]%x) query(root*2+1,mid+1,r,xl,xr,x); 
}
int main(){
    cin>>n;
    build(1,1,n); 
    int m;cin>>m;
    while(m--){
        int a;cin>>a;
        if(a==1){
            int l,r,x;
            scanf("%d%d%d",&l,&r,&x);
            cnt=0;query(1,1,n,l,r,x);
            if(cnt<=1) puts("YES");
            else puts("NO");
        }
        else {
            int pos,x;
            scanf("%d%d",&pos,&x);
            update(1,1,n,pos,x);
        }
    }
    return 0;
}

 

标签:Tough,gcd,int,Puzzle,tree,CodeForces,mid,return,root
来源: https://www.cnblogs.com/Accepting/p/12634028.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有