HDU 5726 区间GCD (ST + 二分 +尺取+思维)

GCD

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 5030    Accepted Submission(s): 1800


Problem Description
Give you a sequence of N(N100,000) integers : a1,...,an(0<ai1000,000,000). There are Q(Q100,000) queries. For each query l,r you have to calculate gcd(al,,al+1,...,ar) and count the number of pairs (l,r)(1l<rN)such that gcd(al,al+1,...,ar) equal gcd(al,al+1,...,ar).
 

Input
The first line of input contains a number T, which stands for the number of test cases you need to solve.

The first line of each case contains a number N, denoting the number of integers.

The second line contains N integers, a1,...,an(0<ai1000,000,000).

The third line contains a number Q, denoting the number of queries.

For the next Q lines, i-th line contains two number , stand for the li,ri, stand for the i-th queries.
 

Output
For each case, you need to output “Case #:t” at the beginning.(with quotes, t means the number of the test case, begin from 1).

For each query, you need to output the two numbers in a line. The first number stands for gcd(al,al+1,...,ar) and the second number stands for the number of pairs (l,r) such that gcd(al,al+1,...,ar) equal gcd(al,al+1,...,ar).
 

Sample Input
 
  
1 5 1 2 4 6 7 4 1 5 2 4 3 4 4 4
 

Sample Output
 
  
Case #1: 1 8 2 4 2 4 6 1
 

Author
HIT
 

Source
/**
题意:给定一个长度为n的序列a   
l r 表示[l,r]的连续区间
问:gcd(l,l+1,l+2.....r)=ans;
a序列中存在多少个连续区间使得该连续区间的gcd等于ans;

解题思路:对于一段连续区间的gcd  可由RMQ直接得到 
由于求解的是子区间的数量 然而对于连续区间子序列gcd值不同数的个数 为lgn级别的 并且这些数是发散的 (1e9的数据)
因此可以采用最暴力的方法map进行存储答案 最后O(1)查询;
中间过程状态 : 固定左端点  枚举右端点 看在此gcd下的区间长度能达到的最大长度 并实时用map进行记录 二分性质为:最小值最大化;
动态更新gcd的过程就是类似于尺取法的过程
***tricks****
ST表的处理注意角标的变化; 
时间复杂度 n*lgn*lgn
*/

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxn=1e6+7;
int n,dp[maxn][20];

int gcd(int a,int b){return b==0?a:gcd(b,a%b);}

void init(){
	for(int j=1;(1<<j)<=n;j++){
		for(int i=1;i+(1<<j)-1<=n;i++){
			dp[i][j]=gcd(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
		}
	}
}

int query(int l,int r){
	int k=(int)(log10(r*1.0-l*1.0+1)/log10(2.0));
	return gcd(dp[l][k],dp[r-(1<<k)+1][k]);
}

map<int,ll>mp;

void solve(){
	mp.clear();
	for(int i=1;i<=n;i++){
		int tmp=dp[i][0],j=i;
		while(j<=n){
			int l=j,r=n;
			while(l<r){
				int mid=l+r+1>>1;
				if(query(i,mid)==tmp) l=mid;
				else r=mid-1;
			}
			mp[tmp]+=(l-j+1);
			j=l+1;
			tmp=query(i,j);
		}
	}
}

void solved(){
	int t;scanf("%d",&t);
	for(int cas=1;cas<=t;cas++){
		scanf("%d",&n);
		for(int i=1;i<=n;i++) scanf("%d",&dp[i][0]);
		init();
		solve();
		printf("Case #%d:\n",cas);
		int q;scanf("%d",&q);
		while(q--){
			int l,r;scanf("%d %d",&l,&r);
			int ret=query(l,r);
			printf("%d %lld\n",ret,mp[ret]);
		}
	}
}

int main (){
	solved();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hypHuangYanPing/article/details/80962973