题目和题解请见刘汝佳紫皮书340页。
代码中用了STL中的map。也是现在才知道到map在系统中是以pair的形式存储的,first是键值,second是对应的映射值。
map的遍历仍然是使用类的迭代器。
代码如下:
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<map>
#define LL long long
using namespace std;
const LL maxn=100000+5;
LL n;
map<LL,LL> mp;
inline void _read(LL &x){
char ch=getchar(); bool mark=false;
for(;!isdigit(ch);ch=getchar())if(ch=='-')mark=true;
for(x=0;isdigit(ch);ch=getchar())x=x*10+ch-'0';
if(mark)x=-x;
}
LL gcd(LL x,LL y){
return y? gcd(y,x%y): x;
}
int main(){
LL i,j,T;
_read(T);
while(T--){
LL ans=0,x;
_read(n);
mp.clear();
for(i=1;i<=n;i++){
_read(x);
if(!mp.count(x))mp[x]=i;
map<LL,LL>::iterator it;
for(it=mp.begin();it!=mp.end();){
LL cur=gcd(x,it->first);
ans=max(ans,cur*(i-it->second+1));
if(!mp.count(cur)) mp[cur]=it->second;
else mp[cur]=min(mp[cur],it->second);
if(cur<it->first)mp.erase(it++);
else it++;
}
}
cout<<ans<<endl;
}
return 0;
}
以下是对区间问题的一点总结:
方法一: 区间转点
一般是和或者差之类的问题,通过前缀和可以转化为点的问题。
方法二: 确定一边端点
代码中一般用枚举其中一个端点来体现。
这种题目的重点在于转移,总是要维护一个和答案有关的东西(就像本题中的那个map),要考虑如果给定的那个端点移动会造成什么影响。一般会用到线段树之类的数据结构来维护,例如以下两题:
(1) Mex II
(2)Codeforces Round #365 (Div. 2) D (线段树)
方法三:写累了不想写了