跳到正文

题解

题解:P5502 [JSOI2015] 最大公约数

limingyuan333约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年9月12日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 2 分钟
获赞
1
题目
P5502

版本

  1. v2当前
  2. v1

题意:

求 W(L,R)=(R−L+1)×gcd⁡(Al,…,Ar)W(L,R) = (R-L+1) × \gcd (A_l,\dots,A_r) 的最大值。

思路

子序列问题通常可以使用分治算法来解决,我们考虑怎样算左右区间中间的值,发现 gcd⁡\gcd 的个数不超过 log⁡V\log V 于是可以暴力找出所有的的 gcd⁡\gcd 处在的离中间最远的位置,暴力计算每一对即可。

C++
#include<bits/stdc++.h>
#define int long long
#define mk make_pair
#define pii pair<int,int>
#define fi first
#define se second
using namespace std;
const int MAXN=2e5+10;
int n,a[MAXN],res,c[MAXN];
void solve(int l,int r){
	if(l==r) return res=max(res,a[l]),void();
	int mid=l+r>>1;
	solve(l,mid);solve(mid+1,r);
	int now=a[mid+1];unordered_map<int,int>mpr,mpl;mpr[now]=mid+1;
	for(int i=mid+2;i<=r;i++) {
		now=__gcd(now,a[i]),mpr[now]=i;
	}now=a[mid];mpl[now]=mid;
	for(int i=mid-1;i>=l;i--) now=__gcd(now,a[i]),mpl[now]=i;
	for(auto x:mpl){
		for(auto y:mpr){
			res=max(res,__gcd(x.fi,y.fi)*(y.se-x.se+1));
		}
	}
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(NULL),cout.tie(NULL);
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	solve(1,n);cout<<res;
	return 0;
}
原文