This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct Line {
mutable i64 k, m, p;
bool operator<(const Line &o) const { return k < o.k; }
bool operator<(i64 x) const { return p < x; }
};
struct LineContainer : multiset<Line, less<>> {
// (for doubles, use inf = 1/.0, div(a,b) = a/b)
static const i64 inf = LLONG_MAX;
i64 div(i64 a, i64 b) { // floored division
return a / b - ((a ^ b) < 0 && a % b);
}
bool isect(iterator x, iterator y) {
if (y == end())
return x->p = inf, 0;
if (x->k == y->k)
x->p = x->m > y->m ? inf : -inf;
else
x->p = div(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
void add(i64 k, i64 m) {
auto z = insert({k, m, 0}), y = z++, x = y;
while (isect(y, z))
z = erase(z);
if (x != begin() && isect(--x, y))
isect(x, y = erase(y));
while ((y = x) != begin() && (--x)->p >= y->p)
isect(x, erase(y));
}
i64 query(i64 x) {
assert(!empty());
auto l = *lower_bound(x);
return l.k * x + l.m;
}
};
int main() {
cin.tie(0)->sync_with_stdio(0);
int N;
cin >> N;
vector<i64> h(N), W(N);
copy_n(istream_iterator<i64>(cin), N, begin(h));
copy_n(istream_iterator<i64>(cin), N, begin(W));
partial_sum(begin(W), end(W), begin(W));
LineContainer cht;
cht.add(2 * h[0], W[0] - h[0] * h[0]);
auto dp = 0LL;
for (auto i = 1; i < N; ++i) {
dp = h[i] * h[i] + W[i - 1] - cht.query(h[i]);
cht.add(2 * h[i], W[i] - h[i] * h[i] - dp);
}
cout << dp;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |