牛客 545A 小A与最大子段和 & CF 660F Bear and Bowling 4
大意: 给定序列$a$, 求选择一个子区间$[l,r]$, 使得$\sum\limits_{i=l}^r(i-l+1)a_i$最大.
$n\le2e5, |a_i|\le 1e7$.
记$s[i]=\sum a[i], m[i]=\sum ia[i]$, $dp[i]$为以$i$为右端点的答案, 有
$\begin{align} \notag dp[i] & =\max\limits_{0\le j<i}\{m[i]-m[j]-j(s[i]-s[j])\} \\ & = m[i]-\min\limits_{0\le j<i}\{m[j]-js[j]+js[i]\} \notag\end{align}$
然后斜率优化.
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl '\n' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 1e6+10; int n, a[N], q[N]; ll s[N], m[N], dp[N], g[N]; double slope(int i, int j) { return ((double)g[i]-g[j])/(i-j); } int main() { scanf("%d", &n); REP(i,1,n) { scanf("%d", a+i); s[i] = s[i-1]+a[i]; m[i] = m[i-1]+(ll)i*a[i]; g[i] = (ll)i*s[i]-m[i]; } q[++*q] = 0; ll ans = -1e18; REP(i,1,n) { int opt=1,l=2,r=*q; while (l<=r) { if (slope(q[mid],q[mid-1])>=s[i]) opt=mid,l=mid+1; else r=mid-1; } ans = max(ans, m[i]-m[q[opt]]-(ll)q[opt]*(s[i]-s[q[opt]])); while (*q>1&&slope(i,q[*q])>slope(q[*q],q[*q-1])) --*q; q[++*q] = i; } printf("%lld\n", ans); }