首页 技术 正文
技术 2022年11月9日
0 收藏 526 点赞 3,311 浏览 1887 个字

很经典的题目,愣是没做出来。。

题意:给出一个序列,求一子序列,满足其GCD(子序列)* length(子序列)最大。

题解:

  类似单调队列的思想,每次将前面所得的最大公约数与当前数进行GCD,若GCD变小,则将原来的最大公约数替换成当前GCD,因为原来的已经不可能取到了。

  实现时利用的是STL中的map。另外经WLM牛的指点,得知map在遍历时插入删除是十分危险的操作,最后用滚动map实现。

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <set>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)>(y)?(y):(x))
#define INF 0x3f3f3f3f
#define LL long longusing namespace std;LL ans, a;
int n, t;
map<LL, LL> mapp[];LL gcd(LL a, LL b)
{
return b?gcd(b, a%b):a;
}int main()
{
scanf("%d", &t);
while(t--)
{
ans=;
scanf("%d", &n);
int k=;
mapp[k].clear();
for(int i=; i<=n; i++, k^=)
{
scanf("%I64d", &a);
mapp[!k].clear();
ans=max(ans, a);
if(mapp[!k].find(a)==mapp[!k].end())
mapp[!k][a]=i;
for(map<LL, LL>::iterator it=mapp[k].begin(); it != mapp[k].end(); it++)
{
LL tmp=gcd(a, it->first);
ans=max(ans, tmp*(i-it->second+));
if(mapp[!k].find(tmp)==mapp[!k].end())
mapp[!k][tmp]=it->second;
else if(mapp[!k][tmp]>it->second)
mapp[!k][tmp]=it->second;
}
}
printf("%I64d\n", ans);
}
return ;
}

当然不用滚动也可以,因为加入的元素都小于当前元素,不会影响到后面,其次删除时 用 map.erase(it++)就可以了

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <set>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)>(y)?(y):(x))
#define INF 0x3f3f3f3f
#define LL long longusing namespace std;LL ans, a;
int n, t;
map<LL, LL> mapp;LL gcd(LL a, LL b)
{
return b?gcd(b, a%b):a;
}int main()
{
scanf("%d", &t);
while(t--)
{
ans=;
scanf("%d", &n);
mapp.clear();
for(int i=; i<=n; i++)
{
scanf("%I64d", &a);
if(mapp.find(a) == mapp.end())
mapp[a]=i;
for(map<LL, LL>::iterator it=mapp.begin(); it != mapp.end(); )
{
LL tmp=gcd(a, it->first);
ans=max(ans, tmp*(i-it->second+));
if(mapp.find(tmp) == mapp.end())
mapp[tmp]=it->second;
else
mapp[tmp]=min(mapp[tmp], it->second);
if(tmp<it->first)
mapp.erase(it++);
else
it++;
}
}
printf("%I64d\n", ans);
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294