题解 CF631E 【Product Sum】
//20200804update:抱歉,提交次数有点多是因为Markdown爆炸了(本机AC提交RE那种),带来的麻烦请管理员谅解。
【前言】
似乎楼下那篇斜率优化没有A啊。。。那是不是我这篇AC了的更有发言权呢?而且写法显然要好得多,码量似乎是楼下的一半。
【题意】
题意似乎挺简单的,给你
【思路】
首先我们考虑
很显然,由于我们只移动一个数,因此只需要枚举起点
这里我们分类讨论。
对于
其中
对于
具体的推导就不再赘述了,与上文类似,留给读者自行思考。
【化简】
我们发现这甚至不是一个
考虑设
我们有:
结果写完现在的两个式子之后,我们发现了一些很有趣的事情:
于是我们惊奇地发现两个式子完 全 一 致。
因此码量大 大 减 少(有用部分大概
【优化】
式子化简完了,考虑优化。
这个式子符合斜率优化的特点,显然可以斜率优化。
考虑化开,不妨设
有:
移项、消元得:
设斜率
由于一开始所有
【代码】
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
typedef unsigned int UI;
template <typename T>
inline void read(T &x){
x = 0;int fu = 1;
char c = getchar();
while(c > 57 || c < 48){
if(c == 45) fu = -1;
c = getchar();
}
while(c <= 57 && c >= 48){
x = (x << 3) + (x << 1) + c - 48;
c = getchar();
}
x *= fu;
}
template <typename T>
inline void fprint(T x){
if(x < 0) putchar(45), x = -x;
if(x > 9) fprint(x / 10);
putchar(x % 10 + 48);
}
template <typename T>
inline void fprint(T x, char ch){
fprint(x);putchar(ch);
}
template <typename T>
inline T min(T x, T y) {return x < y ? x : y;}
template <typename T>
inline T max(T x, T y) {return x > y ? x : y;}
template <typename T>
inline void chmin(T &x, T y) {(x > y) && (x = y);}
template <typename T>
inline void chmax(T &x, T y) {(x < y) && (x = y);}
//有效代码从这里开始
LL b[200010], n, a[200010], ans = 0, ret = 0;
int ed = 1, q[200010];
inline LL X(int x) {return x;}
inline LL Y(int x) {return b[x];}
inline LL slope_fz(int x, int y) {return Y(x) - Y(y);}//维护斜率,写分子分母的原因在于这样可以避免精度爆炸
inline LL slope_fm(int x, int y) {return X(x) - X(y);}
inline int solve (LL val){//二分找斜率
int L = 2, R = ed, cur = 1;
while(L <= R){
int mid = (L + R) >> 1;
if(slope_fz(q[mid], q[mid - 1]) <= val * slope_fm(q[mid], q[mid - 1])) L = mid + 1, cur = mid;
else R = mid - 1;
}
return q[cur];
}
int main(){
read(n);
for (register int i = 1;i <= n;i ++){read(a[i]);b[i] = b[i - 1] + a[i];ans = ans + i * a[i];}//求前缀和与原序列权值(毕竟是在此基础上增加)
for (register int i = 1;i <= n;i ++){//每个j入队
while(ed > 1 && slope_fz(q[ed], q[ed - 1]) * slope_fm(i, q[ed]) >= slope_fz(i, q[ed]) * slope_fm(q[ed], q[ed - 1])) ed --;
q[++ ed] = i;
}
for (register int i = 1;i <= n;i ++){//每个i扫一遍
int j = solve(a[i]);
chmax(ret, (j - i) * a[i] + b[i] - b[j]);
}
fprint(ans + ret);putchar(10);
}