hdu 5869 Different GCD Subarray Query(gcd+树状数组)

Different GCD Subarray Query

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 114    Accepted Submission(s): 29



Problem Description
This is a simple problem. The teacher gives Bob a list of problems about GCD (Greatest Common Divisor). After studying some of them, Bob thinks that GCD is so interesting. One day, he comes up with a new problem about GCD. Easy as it looks, Bob cannot figure it out himself. Now he turns to you for help, and here is the problem:
  
  Given an array a of N positive integers a1,a2,aN1,aN; a subarray of a is defined as a continuous interval between a1 and aN. In other words, ai,ai+1,,aj1,aj is a subarray of a, for 1ijN. For a query in the form (L,R), tell the number of different GCDs contributed by all subarrays of the interval [L,R].
  
 

Input
There are several tests, process till the end of input.
  
  For each test, the first line consists of two integers N and Q, denoting the length of the array and the number of queries, respectively. N positive integers are listed in the second line, followed by Q lines each containing two integers L,R for a query.

You can assume that
  
     1N,Q100000
    
   1ai1000000
 

Output
For each query, output the answer in one line.
 

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

Sample Output
 
   
6 6 6
 

Source
2016 ACM/ICPC Asia Regional Dalian Online


题意:长度n的序列, m个询问区间[L, R], 问区间内的所有子段的不同GCD值有多少种.


题解:考虑固定左端点的不同GCD值,只有不超过logA种, 所以事件点只有nlogA个. 那么离线处理, 按照区间右端点排序从小到大处理询问,

用一个树状数组维护每个GCD值的最大左端点位置即可. 复杂度是O(nlogAlogn).


这份题解里有两个难点:

1、如何快速的离线化处理出固定的左端点的gcd;

2   如何用树状数组维护最大左端点,又如何求出答案??


第一个问题:

很显然,若是平常的离散处理,时间复杂度为n^2;

        for(int i=1;i<=n;i++)
        {
            int x=num[i],y=i;
            for(int j=0;j
这个方式我也是第一次见,将固定的左端点和得出的gcd同存在右端点,这样的确可以做到nlongA的时间离线处理。

而且这种方式存储的gcd值是从小到大的,所以不会有重存的情况出现。

主要是我不太习惯在vector 数组里用pair ,真是汗颜。。。


如何维护最大左端点呢??

首先对查询进行右端点排序。

从左到右遍历一遍节点的gcd值。

并在树状数组里面更新相同gcd的最由端点。


代码:

#include
using namespace std;
const int maxn=100100;
int c[maxn];
vector< pair >gg[maxn];
int num[maxn],vis[maxn*10],res[maxn];
struct node
{
    int l,r,id;
    bool operator<(const node&p)const
    {
        return r







你可能感兴趣的:(树状数组)