hdu_5726_GCD(线段树维护区间+预处理)
题目链接:hdu_5726_GCD
题意:
给你n个数(n<=1e5)然后m个询问(m<=1e5),每个询问一个区间,问你这个区间的GCD是多少,并且输出从1到n有多少个区间的GCD和这个区间的相同
题解:
对于第一个问,直接上线段树维护一下区间GCD就行了,对于第二个问,直接上区间GCD维护的板子。
1 #include<cstdio> 2 #include<algorithm> 3 #include<map> 4 #define ls l,m,rt<<1 5 #define rs m+1,r,rt<<1|1 6 using namespace std; 7 typedef long long ll; 8 map<int,ll>mp; 9 const int N=1e5+7; 10 int n,i,j,a[N],l[N],v[N],tr[N<<2]; 11 12 void init(){ 13 mp.clear(); 14 scanf("%d",&n); 15 for(int i=1;i<=n;i++)scanf("%d",a+i); 16 for(int i=1;i<=n;i++)for(v[i]=a[i],j=l[i]=i;j;j=l[j]-1){ 17 v[j]=__gcd(v[j],a[i]); 18 while(l[j]>1&&__gcd(a[i],v[l[j]-1])==__gcd(a[i],v[j]))l[j]=l[l[j]-1]; 19 mp[v[j]]+=j-l[j]+1; 20 } 21 } 22 23 void build(int l=1,int r=n,int rt=1){ 24 if(l==r){tr[rt]=a[l];return;} 25 int m=(l+r)>>1; 26 build(ls),build(rs); 27 tr[rt]=__gcd(tr[rt<<1],tr[rt<<1|1]); 28 } 29 30 int ask(int L,int R,int l=1,int r=n,int rt=1){ 31 if(L<=l&&r<=R)return tr[rt]; 32 int m=(l+r)>>1; 33 if(R<=m)return ask(L,R,ls); 34 if(L>m)return ask(L,R,rs); 35 return __gcd(ask(L,R,ls),ask(L,R,rs)); 36 } 37 38 int main(){ 39 int t,ic=1,k,x,y; 40 scanf("%d",&t); 41 while(t--){ 42 init(),build(); 43 scanf("%d",&k); 44 printf("Case #%d:\n",ic++); 45 while(k--){ 46 scanf("%d%d",&x,&y); 47 int tp=ask(x,y); 48 printf("%d %lld\n",tp,mp[tp]); 49 } 50 } 51 return 0; 52 }

浙公网安备 33010602011771号