Given an integer sequence a1,a2,⋯,an𝑎1,𝑎2,⋯,𝑎𝑛 of length n𝑛 and a non-negative integer k𝑘, you can perform the following operation at most once: Choose two integers l𝑙 and r𝑟 such that 1≤l≤r≤n1≤𝑙≤𝑟≤𝑛, then for each l≤i≤r𝑙≤𝑖≤𝑟, change ai𝑎𝑖 into (ai+k)(𝑎𝑖+𝑘).
Maximize the greatest common divisor of the whole sequence.
An integer g𝑔 is said to be the common divisor of the whole sequence, if ai𝑎𝑖 is divisible by g𝑔 for all 1≤i≤n1≤𝑖≤𝑛.
Input
There are multiple test cases. The first line of the input contains an integer T𝑇 indicating the number of test cases. For each test case:
The first line contains two integers n𝑛 and k𝑘 (1≤n≤3×1051≤𝑛≤3×105, 0≤k≤10180≤𝑘≤1018).
The second line contains n𝑛 integers a1,a2,⋯,an𝑎1,𝑎2,⋯,𝑎𝑛 (1≤ai≤10181≤𝑎𝑖≤1018) indicating the sequence.
It's guaranteed that the sum of n𝑛 of all test cases does not exceed 3×1053×105.
Output
For each test case output one line containing one integer indicating the maximum greatest common divisor of the whole sequence.
暴力写法:
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N=3e5+5;
int n,k,a[N],head[N],tail[N];
void solve()
{
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
tail[n+1]=0;
for(int i=1;i<=n;i++) head[i]=__gcd(head[i-1],a[i]);
for(int i=n;i>=1;i--) tail[i]=__gcd(tail[i+1],a[i]);
int ans=1;
for(int l=1;l<=n;l++)
{
//if(head[l]>=head[l-1]&&l!=1) continue;
int g=0;
for(int r=l;r<=n;r++)
{
g=__gcd(g,a[r]+k);
ans=max(ans,__gcd(head[l-1],__gcd(g,tail[r+1])));
}
}
cout<<max(ans,head[n])<<endl;
}
signed main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int T;
cin>>T;
while(T--) solve();
return 0;
}
把注释的那一行去掉就变成O(n*logn)的算法了
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N=3e5+5;
int n,k,a[N],head[N],tail[N];
void solve()
{
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
tail[n+1]=0;
for(int i=1;i<=n;i++) head[i]=__gcd(head[i-1],a[i]);
for(int i=n;i>=1;i--) tail[i]=__gcd(tail[i+1],a[i]);
int ans=1;
for(int l=1;l<=n;l++)
{
if(head[l]>=head[l-1]&&l!=1) continue;
int g=0;
for(int r=l;r<=n;r++)
{
g=__gcd(g,a[r]+k);
ans=max(ans,__gcd(head[l-1],__gcd(g,tail[r+1])));
}
}
cout<<max(ans,head[n])<<endl;
}
signed main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int T;
cin>>T;
while(T--) solve();
return 0;
}