Magical GCD UVA - 1642

本文解析了一道经典的紫书数论题目,探讨了给定正整数序列中gcd(ai,ai+1,…,aj)*(j-i+1)最大值的求解方法。通过动态扫描区间,维护每个gcd及其索引,实现高效算法。

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

紫书上的数论经典题。题意大概是这样的,给一段正整数序列,问gcd(a i,a i+1,…,a j)*(j-i+1)的最大值。
其实不能,就是右端点从前往右扫,遍历整个区间,左端点从右端点往左扫,直到起点。数据维护每个gcd,index.
反正核心就是相同gcd的删掉,时间复杂度大概就是nlong(ai)

/************************************************
┆  ┏┓   ┏┓ ┆
┆┏┛┻━━━┛┻┓ ┆
┆┃       ┃ ┆
┆┃   ━   ┃ ┆
┆┃ ┳┛ ┗┳ ┃ ┆
┆┃       ┃ ┆
┆┃   ┻   ┃ ┆
┆┗━┓    ┏━┛ ┆
┆  ┃    ┃  ┆      
┆  ┃    ┗━━━┓ ┆
┆  ┃  AC代马   ┣┓┆
┆  ┃           ┏┛┆
┆  ┗┓┓┏━┳┓┏┛ ┆
┆   ┃┫┫ ┃┫┫ ┆
┆   ┗┻┛ ┗┻┛ ┆
************************************************ */
#pragma warning (disable:4996)
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<set>
#include<list>
#include<map>
#include<stack>
#include<cstdlib>
#include<functional>
using namespace std;
typedef  long long ll;
#define INF 0x3f3f3f3f
const int maxn = 1e5 + 10;
struct node
{
	ll gcd;
	int index;
}a[maxn];
list<node> lt;
ll __gcd(ll aa,ll bb)
{
	if(bb==0)
		return aa;
	return __gcd(bb,aa%bb);
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			scanf("%lld",&a[i].gcd);
			a[i].index=i;
		}
		lt.clear();
		ll ans=0;
		for(int i=1;i<=n;i++)
		{
			ans=max(a[i].gcd,ans);
			ll &x=a[i].gcd;
			for(list<node> :: iterator it=lt.begin(),that;it!=lt.end();it++)
			{
				it->gcd=__gcd(it->gcd,x);
				that=it;
				that++;
				while(that!=lt.end())
				{
					that->gcd=__gcd(that->gcd,x);
					if(that->gcd==it->gcd)
					{
						lt.erase(it);
						it=that;
						that++;
					}
					else
						break;
				}
				ans=max(ans,(i - it->index + 1)*it->gcd);
			}
			lt.push_front(a[i]);
		}
		printf("%lld\n",ans);
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_44508514

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值