/*http://acm.hdu.edu.cn/showproblem.php?pid=4630
No Pain No Game
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 689 Accepted Submission(s): 295
Problem Description
Life is a game,and you lose it,so you suicide.
But you can not kill yourself before you solve this problem:
Given you a sequence of number a1, a2, ..., an.They are also a permutation of 1...n.
You need to answer some queries,each with the following format:
If we chose two number a,b (shouldn't be the same) from interval [l, r],what is the maximum gcd(a, b)? If there's no way to choose two distinct number(l=r) then the answer is zero
Input
First line contains a number T(T <= 5),denote the number of test cases.
Then follow T test cases.
For each test cases,the first line contains a number n(1 <= n <= 50000).
The second line contains n number a1, a2, ..., an.
The third line contains a number Q(1 <= Q <= 50000) denoting the number of queries.
Then Q lines follows,each lines contains two integer l, r(1 <= l <= r <= n),denote a query.
Output
For each test cases,for each query print the answer in one line.
Sample Input
1
10
8 2 4 9 5 7 10 6 1 3
5
2 10
2 4
6 9
1 4
7 10
Sample Output
5
2
2
4
3
Source
2013 Multi-University Training Contest 3
Recommend
zhuyuanchen520
Statistic | Submit | Discuss | Note
Home | Top Hangzhou Dianzi University Online Judge 3.0
Copyright © 2005-2013 HDU ACM Team. All Rights Reserved.
解析:
题意:给出一组数,输出给定区间的约数最大值
思路:数学+树状数组
1.将查询区间进行排序处理
2。枚举每个数的约数进行树状数组的更新和维护
3.利用树状数组查询结果
PS:查询和更新分过程与查询区间排序紧密相关
具体思路以下博客
656MS 1596K 1414 B C+
http://www.cnblogs.com/kuangbin/p/3225627.html
http://blog.csdn.net/acm18810549519/article/details/9633731
*/
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=50000+10;
int n,a[maxn];
int c[maxn],pre[maxn],ans[maxn];
struct query
{
int s;
int t;
int id;
}q[maxn];
int max(int a,int b)
{
return a>b? a:b;
}
bool cmp(query q1,query q2)
{
return q1.t<q2.t;
}
int lowbit(int x)
{
return (x&(-x));
}
void update(int x,int d)//从上到下更新
{
while(x>0)
{
c[x]=max(c[x],d);
x-=lowbit(x);
}
}
int findmax(int x)//从下到上查询
{int ret=0;
while(x<=n)
{
ret=max(c[x],ret);
x+=lowbit(x);
}
return ret;
}
int main()
{
int T,i,j,m,k;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(j=1;j<=m;j++)
{scanf("%d%d",&q[j].s,&q[j].t);
q[j].id=j;
}
sort(q+1,q+1+m,cmp);
memset(c,0,sizeof(c));
memset(pre,0,sizeof(pre));
memset(ans,0,sizeof(ans));
k=1;
for(i=1;i<=n;i++)
{
for(j=1;j*j<=a[i];j++)//枚举每个约数
{
if(a[i]%j==0)
{
if(pre[j])//由于要至少有两个数才可以组成公约数,所以此时必须在该位置上已经存在约数的情况下,更新才有效果
update(pre[j],j);
pre[j]=i;
if(j!=a[i]/j)//如果
{int t=a[i]/j;
if(pre[t])
update(pre[t],t);//理由同上
pre[t]=i;
}
}
}
while(i==q[k].t&&k<=m)//终点相同则可以根据起点一一查询(因为终点之后的数据还未更新)
{
ans[q[k].id]=findmax(q[k].s);
k++;
}
}
for(i=1;i<=m;i++)
printf("%d\n",ans[i]);
}
return 0;
}