GCD Problem

本文介绍了一种使用线段树数据结构解决区间查询和更新问题的方法,具体为区间查询最大公约数(GCD)及区间平方根更新操作。通过记录区间是否全为1的状态,避免了时间复杂度过高的情况,提高了查询效率。

https://ac.nowcoder.com/acm/contest/877/F

题意:区间查询gcd,区间开方修改;

思路:线段树;要记录如果一个区间全都是1就直接返回1,否则会tle;查询单点是注意gcd不了; 

#include<algorithm>
#include<set>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<iostream>
#include<set>
#include<vector>
#include<queue>
#include<cmath>
#include<cstdio>
#include<map>
#include<stack>
#include<string>
#include<bits/stdc++.h>
using namespace std;

#define sfi(i) scanf("%d",&i)
#define pri(i) printf("%d\n",i)
#define sff(i) scanf("%lf",&i)
#define ll long long
#define ull unsigned long long
#define mem(x,y) memset(x,y,sizeof(x))
#define INF 0x3f3f3f3f
#define eps 1e-16
#define PI acos(-1)
#define lowbit(x) ((x)&(-x))
#define zero(x) (((x)>0?(x):-(x))<eps)
#define fl() printf("flag\n")
#define MOD(x) ((x%mod)+mod)%mod
#define endl '\n'
#define pb push_back
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)

const int maxn=2e5+9;
const int mod=1e9+7;

inline ll read()
{
    ll f=1,x=0;
    char ss=getchar();
    while(ss<'0'||ss>'9')
    {
        if(ss=='-')f=-1;ss=getchar();
    }
    while(ss>='0'&&ss<='9')
    {
        x=x*10+ss-'0';ss=getchar();
    }    return f*x;
}


int n;
ll tree[maxn*4];
bool yi[maxn*4];

void push(int rt)
{
    tree[rt]=__gcd(tree[rt<<1],tree[rt<<1|1]);
    yi[rt]=yi[rt<<1]&&yi[rt<<1|1];
}

void build(int l,int r,int rt)
{
    if(l==r)
    {
        cin>>tree[rt];
        return ;
    }
    int mid=(l+r)>>1;
    //ll mid=l+(r-l)>>1;
    build(l,mid,rt<<1);
    build(mid+1,r,rt<<1|1);
    push(rt);
}

void update(int l,int r,int L,int R,int rt)
{
    if(yi[rt]) return ;
    if(l==r)
    {
        tree[rt]=sqrt(tree[rt]);
        if(tree[rt]==1) yi[rt]=1;
        return ;
    }
    int mid=(l+r)>>1;
    if(L<=mid) update(l,mid,L,R,rt<<1);
    if(R>mid) update(mid+1,r,L,R,rt<<1|1);
    push(rt);
}

ll query(int l,int r,int L,int R,int rt)
{
    if(yi[rt]) return 1LL;
    if(L<=l&&R>=r) return tree[rt];
    int mid=(l+r)>>1;
    ll tmp1=0,tmp2=0;
    if(L<=mid)
    {
        tmp1=query(l,mid,L,R,rt<<1);
    }
    if(R>mid)
    {
        tmp2=query(mid+1,r,L,R,rt<<1|1);
    }
    if(tmp1==0) return tmp2;
    else if(tmp2==0) return tmp1;
    else return __gcd(tmp1,tmp2);
}

int main()
{
    //FAST_IO;
    //freopen("input.txt","r",stdin);

    cin>>n;
    build(1,n,1);

    int q;
    cin>>q;
    while(q--)
    {
        int op;
        int l,r;
        cin>>op>>l>>r;
        if(op)
        {
            cout<<query(1,n,l,r,1)<<endl;
        }
        else
        {
            update(1,n,l,r,1);
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值