제출 #677147

#제출 시각아이디문제언어결과실행 시간메모리
677147leeh18Building Bridges (CEOI17_building)C++17
100 / 100
46 ms8920 KiB
#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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...