British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends."
It turns out that positive integers can also be friends with each other! You are given an array aa of distinct positive integers.
Define a subarray ai,ai+1,…,ajai,ai+1,…,aj to be a friend group if and only if there exists an integer m≥2m≥2 such that aimodm=ai+1modm=…=ajmodmaimodm=ai+1modm=…=ajmodm, where xmodyxmody denotes the remainder when xx is divided by yy.
Your friend Gregor wants to know the size of the largest friend group in aa.
Input
Each test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2⋅1041≤t≤2⋅104).
Each test case begins with a line containing the integer nn (1≤n≤2⋅1051≤n≤2⋅105), the size of the array aa.
The next line contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤10181≤ai≤1018), representing the contents of the array aa. It is guaranteed that all the numbers in aa are distinct.
It is guaranteed that the sum of nn over all test cases is less than 2⋅1052⋅105.
Output
Your output should consist of tt lines. Each line should consist of a single integer, the size of the largest friend group in aa.
Example
input
Copy
4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78
output
Copy
3 3 2 6
Note
In the first test case, the array is [1,5,2,4,6][1,5,2,4,6]. The largest friend group is [2,4,6][2,4,6], since all those numbers are congruent to 00 modulo 22, so m=2m=2.
In the second test case, the array is [8,2,5,10][8,2,5,10]. The largest friend group is [8,2,5][8,2,5], since all those numbers are congruent to 22 modulo 33, so m=3m=3.
In the third case, the largest friend group is [1000,2000][1000,2000]. There are clearly many possible values of mm that work.
思路:
1,询问连续区间的gcd,所以用线段树,又因为找最大,所以是是双指针。
2,具体细节请看代码注释
代码:
const int maxj=2e5+100,mod=1e9+7,nn=33554432;
int a[maxj],b[maxj];
struct node{
int l,r,gcd;
}tree[maxj<<2];
void update(int rt){
tree[rt].gcd=__gcd(tree[rt<<1].gcd,tree[rt<<1|1].gcd);
}
void build(int l,int r,int rt){
tree[rt].l=l;
tree[rt].r=r;
if(l==r){
tree[rt].gcd=b[l];
return ;//一定记着结束!!!!
}
int mid=(l+r)>>1;
build(l,mid,rt<<1);build(mid+1,r,rt<<1|1);
update(rt);
}
int query(int l,int r,int rt){//询问连续区间的gcd
if(l<=tree[rt].l&&r>=tree[rt].r){
return tree[rt].gcd;
}
int mid=(tree[rt].l+tree[rt].r)>>1;//l,r是查找的区间,不能分开,分开树的区间才对
int ret=0;//符合函数类型
if(l<=mid)ret=__gcd(ret,query(l,r,rt<<1));//左子树查找
if(r>=mid+1)ret=__gcd(ret,query(l,r,rt<<1|1));//右子树查找,必须gcd这个ret和查找
return ret;//符合函数类型
}
void solve(){
int n;cin>>n;
for(int i=1;i<=n;++i)cin>>a[i],b[i]=0;//差分数组的使用
if(n==1){
cout<<1<<'\n';//单独一个算是一组
return ;
}
for(int i=1;i<n;++i){
b[i]=abs(a[i+1]-a[i]);
}
build(1,n-1,1);
int mx=0;
for(int ll=1,rr=1;rr<n;rr++){//rr一定加加
if(query(ll,rr,1)>1){
mx=max(rr-ll+1,mx);
}else{
while(query(ll,rr,1)==1)ll++;
}
}
cout<<mx+1<<'\n';
}