hdu 5726 GCD(2016 Multi-University Training Contest 1线段树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5726

题意:给出一组序列a1,a2...an,Q次询问,每次给出l,r ,求出所有满足gcd(l,l+1,...,r)=gcd(l',l+1',...r')的区间个数。


线段树区间查询问题。

利用线段树在logn时间复杂度内求出所有gcd[l,r]的值,并保存在数组里,最后做离线处理。

如果直接线段树在线处理,时间复杂度太高,会直接TLE。

处理时,利用gcd的递减性,合并gcd相同的部分,用nxt数组记录下一个跳跃的位置,最多logn次跳跃,如果从左到右直接扫一遍,n^2的效率显然过不了。

最后特别提醒一下,注意__int64.

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;

template<class T> T gcd(T a, T b) {
    return b ? gcd(b, a % b) : a;
}

#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r

typedef __int64 ll;
const int INF=0x3f3f3f3f;
const int maxn=1e5+10;
int T,n,m;
ll a[maxn],b[maxn];
ll nxt[maxn];
ll v[maxn<<2];
map<int, ll> mpp;

void PushUp(int rt){
    v[rt]=gcd(v[rt<<1],v[rt<<1|1]);
}

void build(int rt,int l,int r){
    if(l==r){
        scanf("%I64d",&v[rt]);
        a[l]=v[rt];
        return ;
    }
    int mid=(l+r)>>1;
    build(lson);
    build(rson);
    PushUp(rt);
}

ll Query(int rt,int l,int r,int L,int R){
    if(L<=l&&r<=R) return v[rt];
    int mid=(l+r)>>1;
    int x=0,y=0;
    if(L<=mid) x=Query(lson,L,R);
    if(R>mid) y=Query(rson,L,R);
    return gcd(x,y);
}

void work(void) {
    int now;
    for(int i = n; i >= 1; i--) {
        now = i;
        for(int j = i; j <= n; j = nxt[j]) {
            a[j] = gcd(a[j], a[now]);
            if(a[j] == a[now]) nxt[now] = nxt[j];
            else now = j;
            if(mpp.count(a[j])) mpp[a[j]] += nxt[j] - j;
            else mpp[a[j]] = nxt[j] - j;
        }
    }
    for(int i = 1; i <= m; i++) printf("%I64d %I64d\n",b[i], mpp[b[i]]);
}

int main(){
    scanf("%d",&T);
    int cas=1;
    while(T--){
        mpp.clear();
        scanf("%d",&n);
        build(1,1,n);
        for(int i = 1; i <= n; i++) nxt[i] = i+1;
        scanf("%d",&m);
        int s,e;
        printf("Case #%d:\n",cas++);
        for(int i=1;i<=m;i++){
            scanf("%d%d",&s,&e);
            b[i]=Query(1,1,n,s,e);
        }
        work();
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值