您的位置:首页 > 大数据 > 人工智能

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

2016-07-19 19:31 555 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: