#include <bits/stdc++.h>
using namespace std;
#define int long long
const int inf = -(1LL << 62);
struct line {
int m, b;
mutable function<const line*() > succ;
bool operator < (const line& rhs) const {
if (rhs.b != inf) return m < rhs.m;
const line* s = succ();
if (!s) return 0;
int x = rhs.m;
return b - s->b < (s->m - m) * x;
}
};
struct CHT : public multiset<line> {
bool bad(iterator y) {
auto z = next(y);
if (y == begin()) {
if (z == end()) return 0;
return y -> m == z -> m && y -> b <= z -> b;
}
auto x = prev(y);
if (z == end()) return y -> m == x -> m && y -> b <= x -> b;
return 1.0 * (x -> b - y -> b) * (z -> m - y -> m) >= 1.0 * (y -> b - z -> b) * (y -> m - x -> m);
}
void add(int m, int b) {
auto y = insert({ m, b });
y->succ = [=, this] { return next(y) == end() ? 0 : &*next(y); };
if (bad(y)) {
erase(y);
return;
}
while (next(y) != end() && bad(next(y))) erase(next(y));
while (y != begin() && bad(prev(y))) erase(prev(y));
}
int query(int x) {
assert(!empty());
auto l = *lower_bound((line) {
x, inf
});
return l.m * x + l.b;
}
};
CHT* cht;
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(nullptr); cout.tie(nullptr);
int n;
cin >> n;
vector<int> h(n + 1, 0), w(n + 1, 0);
for(int i = 1; i <= n; ++i){
cin >> h[i];
}
for(int i = 1; i <= n; ++i){
cin >> w[i];
w[i] += w[i - 1];
}
vector<int> dp(n + 5, 0);
cht = new CHT();
cht -> add (2 * h[1], -(h[1] * h[1] - w[1]));
for(int i = 2; i <= n; ++i){
dp[i] = -cht -> query(h[i]) + h[i] * h[i] + w[i - 1];
cht -> add(2 * h[i], -(dp[i] + h[i] * h[i] - w[i]));
}
cout << dp[n] << "\n";
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |