[BZOJ4488][JSOI2015]最大公约数

结论:固定端点的所有子段GCD只会有$O(\log)$种,因为一个数的质因子个数是这个级别的。

从左到右枚举右端点,用一个数组记录所有GCD相同的子段的第一个位置,每次线性更新与合并。$O(n\log n)$

 1 #include<cstdio>
 2 #include<algorithm>
 3 #define rep(i,l,r) for (int i=(l); i<=(r); i++)
 4 using namespace std;
 5 
 6 typedef long long ll;
 7 const int N=100010;
 8 int n,top,S[N],S2[N];
 9 ll ans,a[N],b[N],b2[N];
10 ll gcd(ll a,ll b){ return b ? gcd(b,a%b) : a; }
11 
12 int main(){
13     scanf("%d",&n);
14     rep(i,1,n) scanf("%lld",&a[i]);
15     rep(i,1,n){
16         S[++top]=i; b[top]=a[i]; int tot=0;
17         for (int j=top-1; j; j--) b[j]=gcd(b[j],b[j+1]);
18         rep(j,1,top) if (b[j]!=b[j-1]) b2[++tot]=b[j],S2[tot]=S[j];
19         rep(j,1,tot) b[j]=b2[j],S[j]=S2[j]; top=tot;
20         rep(j,1,top) ans=max(ans,b[j]*(i-S[j]+1));
21     }
22     printf("%lld\n",ans);
23     return 0;
24 }

 

posted @ 2018-12-02 20:24  HocRiser  阅读(153)  评论(0编辑  收藏  举报