The 2024 ICPC Kunming Invitational Contest E - Relearn through Review

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.

原题链接:Problem - E - Codeforces

暴力写法:

#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;
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值