题解上说的很清楚了,我照着写的,表示膜拜题解
然后时间复杂度我觉得应该是O(nlogn),虽然常数略大,预处理和倒着扫,都是O(nlogn)
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
typedef long long LL;
const int N = 2e5+;
int mat[N],n,mx,tmp,lz[N<<],a[N<<];
LL c[N<<],sum,h[N];
vector<int>v[N];
void build(int rt,int l,int r){
if(l==r){
a[rt]=c[rt]=1ll*l;
return;
}
int m=(l+r)>>;
build(rt<<,l,m);
build(rt<<|,m+,r);
c[rt]=c[rt<<]+c[rt<<|];
a[rt]=min(a[rt<<],a[rt<<|]);
}
void down(int rt,int l,int r){
if(!lz[rt])return;
int m=(l+r)>>;
c[rt<<]=1ll*lz[rt]*(m-l+);
c[rt<<|]=1ll*lz[rt]*(r-m);
a[rt<<]=a[rt<<|]=a[rt];
lz[rt<<]=lz[rt<<|]=lz[rt];
lz[rt]=;
}
void modify(int rt,int l,int r,int x,int y){
if(x<=l&&r<=y){
c[rt]=1ll*tmp*(r-l+);
a[rt]=lz[rt]=tmp;
return;
}
down(rt,l,r);
int m=(l+r)>>;
if(x<=m)modify(rt<<,l,m,x,y);
if(y>m)modify(rt<<|,m+,r,x,y);
c[rt]=c[rt<<]+c[rt<<|];
a[rt]=min(a[rt<<],a[rt<<|]);
}
int ask(int rt,int l,int r,int k){
if(l==r)return l;
int m=(l+r)>>;
if(a[rt<<|]<k)ask(rt<<|,m+,r,k);
else ask(rt<<,l,m,k);
}
int main(){
scanf("%d",&n);
for(int i=;i<=n;++i){
int x;scanf("%d",&x);
mat[x]=i;mx=max(mx,x);
}
for(int i=;i<=mx;++i){
for(int j=i;j<=mx;j+=i)
if(mat[j])
v[i].push_back(mat[j]);
}
for(int i=;i<=mx;++i)
if(v[i].size())sort(v[i].begin(),v[i].end());
build(,,n);
sum=1ll*n*(n+);
for(int i=mx;i>=;--i){
h[i]=sum-c[]; int k=v[i].size();
if(k<)continue;
tmp=n+;
if(v[i][]+<=n){
modify(,,n,v[i][]+,n);
}
tmp=v[i][k-];
if(a[]<tmp){
int pos=ask(,,n,tmp);
pos=min(pos,v[i][]);
if(pos>v[i][])
modify(,,n,v[i][]+,pos);
}
tmp=v[i][k-];
if(a[]<tmp){
int pos=ask(,,n,tmp);
pos=min(pos,v[i][]);
if(pos>)
modify(,,n,,pos);
}
}
LL ans=;
for(int i=;i<=mx;++i)
ans+=1ll*i*(h[i]-h[i-]);
printf("%I64d\n",ans);
return ;
}