src:http://acm.hdu.edu.cn/showproblem.php?pid=5726
解答: http://www.cnblogs.com/WABoss/p/5686994.html
代码:
#include<bits/stdc++.h> using namespace std; #define per(i,a,n) for(int i=a;i < n;i++) #define rep(i,a,n) for(int i=n-1;i>=a;i--) #define Max(a,b) a=max(a,b) #define Min(a,b) a=min(a,b) #define Sz(x) (int)x.size() typedef long long ll; ll gcd(ll a,ll b){while(b){ll t=b;b=a%b;a=t;} return a;} const int inf=0x3f3f3f3f; #define siz 111111 int n,q,l,r; int d[siz][25],mn[siz]; void rmq_init() { for(int j=1;(1<<j)<=n;j++){ for(int i=1;i+(1<<j)-1<=n;i++){ d[i][j]=gcd(d[i][j-1],d[i+(1<<(j-1))][j-1]); } } /*for(int len=1;len<=n;len++){ int k=0; while((1<<(k+1))<=len)k++; mn[len]=k; }*/ } int query(int L,int R) { int k=mn[R-L+1]; return gcd(d[L][k],d[R-(1<<k)+1][k]); } int main() { std::ios::sync_with_stdio(false); int T; for(int len=1;len<=100000;len++){ mn[len]=log2(len)+1e-6; } scanf("%d",&T); for(int cas=1;cas<=T;cas++) { scanf("%d",&n); for(int i=1;i<=n;i++)scanf("%d",&d[i][0]); rmq_init();//nlogn map<int,long long>Mp; int lef,righ; for(int i=1;i<=n;i++){ int g=d[i][0],j=i; while(j<=n){ lef=j,righ=n; while(lef<righ){ int mid=(lef+righ+1)>>1; if(query(i,mid) == g)lef=mid;// else righ=mid-1; } Mp[g]+=(lef-j+1); j=lef+1; g=query(i,j); } } printf("Case #%d: ",cas);// scanf("%d",&q); while(q--){ scanf("%d %d",&l,&r); int k=query(l,r); printf("%d %lld ",k,Mp[k]); } } return 0; }