最大公约数

该博客介绍了一种使用C++实现的高效算法,通过动态维护最大公约数的映射,计算给定数组中每个元素与其他元素的最大公约数之和,其复杂度优化到O(n log n)。核心包括 gcd 函数和利用 map 存储 gcd 的下标信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f, N=1e5+10;
LL gcd(LL a, LL b);

int n;
LL a[N];
map<LL, LL> vn, temp;//gcd映射成下标 
//区间内不同的最大公约数个数为logn个 
signed main()
{
	cin>>n;
	for(int i=1;i<=n;i++) scanf("%lld", &a[i]);
	
	LL res=-INF;
	for(int i=1;i<=n;i++)//固定右端点 
	{
		res=max(res, a[i]);//单独一个数 
		
		for(auto it=vn.begin();it!=vn.end();it++)//遍历枚举以a[i]为右端点的所有gcd. 
		{
			LL now_gcd=gcd(it->first, a[i]);//当前的gcd 
			res=max(res, now_gcd*(i-it->second+1));//取最大值 
			!temp[now_gcd]?temp[now_gcd]=it->second:temp[now_gcd]=min(temp[now_gcd], it->second);
			//如果当前gcd无下标,将左端点下标给他,否则取最远的那个下标 
		}
		
		if(!temp[a[i]]) temp[a[i]]=i;//如果当前一个值, 在vn中没有则放入vn。 
		vn=temp, temp.clear();
	}
	
	cout<<res<<endl;
}

LL gcd(LL a, LL b)
{
	return b?gcd(b, a%b):a;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值