compro_library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub siro53/compro_library

:heavy_check_mark: test/mytest/data-structure/slope-trick.test.cpp

Depends on

Code

#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"
#include "../../../template/template.cpp"
#include "../../../data-structure/slope-trick.hpp"


using Slope = SlopeTrick<ll>;
ll evaluate(Slope s, ll x) {
    ll value = s.eval(x);
    assert(s.size() == 0 && s.L.empty() && s.R.empty());
    return value;
}
int main() {
    Slope zero;
    assert(zero.size() == 0 && zero.min_f == 0 && zero.add_L == 0 && zero.add_R == 0);
    assert(zero.get_min_lr() == make_tuple(0LL, -zero.inf, zero.inf));
    mt19937 rng(62);
    for(int trial = 0; trial < 100; ++trial) {
        Slope base;
        vector<pair<int, int>> terms;
        ll constant = int(rng() % 21) - 10;
        base.add_const(constant);
        for(int i = 0; i < 10; ++i) {
            int kind = rng() % 3, a = int(rng() % 21) - 10;
            terms.emplace_back(kind, a);
            if(kind == 0) base.add_left(a);
            if(kind == 1) base.add_right(a);
            if(kind == 2) base.add_abs(a);
        }
        auto f = [&](ll x) {
            ll value = constant;
            for(auto [kind, a] : terms) {
                if(kind == 0) value += max(0LL, a - x);
                if(kind == 1) value += max(0LL, x - a);
                if(kind == 2) value += abs(x - a);
            }
            return value;
        };
        ll minimum = LLONG_MAX;
        for(int x = -50; x <= 50; ++x) minimum = min(minimum, f(x));
        const auto& view = base;
        auto [value, l, r] = view.get_min_lr();
        assert(view.get_min() == minimum && value == minimum && l <= r);
        for(int x = -30; x <= 30; ++x) {
            assert(evaluate(base, x) == f(x));
            assert((l <= x && x <= r) == (f(x) == minimum));
        }
        auto left = base, right = base, shifted = base, window = base;
        left.clear_right(); right.clear_left(); shifted.shift(-3); window.shift(-2, 4);
        for(int x = -30; x <= 30; ++x) {
            ll a = LLONG_MAX, b = LLONG_MAX, c = LLONG_MAX;
            for(int y = -50; y <= x; ++y) a = min(a, f(y));
            for(int y = x; y <= 50; ++y) b = min(b, f(y));
            for(int y = x - 4; y <= x + 2; ++y) c = min(c, f(y));
            assert(evaluate(left, x) == a && evaluate(right, x) == b);
            assert(evaluate(shifted, x) == f(x + 3) && evaluate(window, x) == c);
        }
        for(bool swap_sizes : {false, true}) {
            auto a = base; Slope b; b.add_abs(3); b.add_const(7);
            if(swap_sizes) a.swap(b);
            a.merge(b);
            assert(b.size() == 0);
            for(int x = -30; x <= 30; ++x) assert(evaluate(a, x) == f(x) + abs(x - 3) + 7);
        }
    }
    INT(a, b); print(a + b);
}
#line 1 "test/mytest/data-structure/slope-trick.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"
#line 1 "template/template.cpp"
// #region Macros
#include <bits/stdc++.h>
using namespace std;
// input output utils
namespace siro53_io {
    // https://maspypy.github.io/library/other/io_old.hpp
    struct has_val_impl {
        template <class T>
        static auto check(T &&x) -> decltype(x.val(), std::true_type{});

        template <class T> static auto check(...) -> std::false_type;
    };

    template <class T>
    class has_val : public decltype(has_val_impl::check<T>(std::declval<T>())) {
    };

    // debug
    template <class T, enable_if_t<is_integral<T>::value, int> = 0>
    void dump(const T t) {
        cerr << t;
    }
    template <class T, enable_if_t<is_floating_point<T>::value, int> = 0>
    void dump(const T t) {
        cerr << t;
    }
    template <class T, typename enable_if<has_val<T>::value>::type * = nullptr>
    void dump(const T &t) {
        cerr << t.val();
    }
    void dump(__int128_t n) {
        if(n == 0) {
            cerr << '0';
            return;
        } else if(n < 0) {
            cerr << '-';
            n = -n;
        }
        string s;
        while(n > 0) {
            s += (char)('0' + n % 10);
            n /= 10;
        }
        reverse(s.begin(), s.end());
        cerr << s;
    }
    void dump(const string &s) { cerr << s; }
    void dump(const char *s) {
        int n = (int)strlen(s);
        for(int i = 0; i < n; i++) cerr << s[i];
    }
    template <class T1, class T2> void dump(const pair<T1, T2> &p) {
        cerr << '(';
        dump(p.first);
        cerr << ',';
        dump(p.second);
        cerr << ')';
    }
    template <class T> void dump(const vector<T> &v) {
        cerr << '{';
        for(int i = 0; i < (int)v.size(); i++) {
            dump(v[i]);
            if(i < (int)v.size() - 1) cerr << ',';
        }
        cerr << '}';
    }
    template <class T> void dump(const set<T> &s) {
        cerr << '{';
        for(auto it = s.begin(); it != s.end(); it++) {
            dump(*it);
            if(next(it) != s.end()) cerr << ',';
        }
        cerr << '}';
    }
    template <class Key, class Value> void dump(const map<Key, Value> &mp) {
        cerr << '{';
        for(auto it = mp.begin(); it != mp.end(); it++) {
            dump(*it);
            if(next(it) != mp.end()) cerr << ',';
        }
        cerr << '}';
    }
    template <class Key, class Value>
    void dump(const unordered_map<Key, Value> &mp) {
        cerr << '{';
        for(auto it = mp.begin(); it != mp.end(); it++) {
            dump(*it);
            if(next(it) != mp.end()) cerr << ',';
        }
        cerr << '}';
    }
    template <class T> void dump(const deque<T> &v) {
        cerr << '{';
        for(int i = 0; i < (int)v.size(); i++) {
            dump(v[i]);
            if(i < (int)v.size() - 1) cerr << ',';
        }
        cerr << '}';
    }
    template <class T> void dump(queue<T> q) {
        cerr << '{';
        while(!q.empty()) {
            dump(q.front());
            if((int)q.size() > 1) cerr << ',';
            q.pop();
        }
        cerr << '}';
    }

    void debug_print() { cerr << endl; }
    template <class Head, class... Tail>
    void debug_print(const Head &h, const Tail &...t) {
        dump(h);
        if(sizeof...(Tail)) dump(' ');
        debug_print(t...);
    }
    // print
    template <class T, enable_if_t<is_integral<T>::value, int> = 0>
    void print_single(const T t) {
        cout << t;
    }
    template <class T, enable_if_t<is_floating_point<T>::value, int> = 0>
    void print_single(const T t) {
        cout << t;
    }
    template <class T, typename enable_if<has_val<T>::value>::type * = nullptr>
    void print_single(const T t) {
        cout << t.val();
    }
    void print_single(__int128_t n) {
        if(n == 0) {
            cout << '0';
            return;
        } else if(n < 0) {
            cout << '-';
            n = -n;
        }
        string s;
        while(n > 0) {
            s += (char)('0' + n % 10);
            n /= 10;
        }
        reverse(s.begin(), s.end());
        cout << s;
    }
    void print_single(const string &s) { cout << s; }
    void print_single(const char *s) {
        int n = (int)strlen(s);
        for(int i = 0; i < n; i++) cout << s[i];
    }
    template <class T1, class T2> void print_single(const pair<T1, T2> &p) {
        print_single(p.first);
        cout << ' ';
        print_single(p.second);
    }
    template <class T> void print_single(const vector<T> &v) {
        for(int i = 0; i < (int)v.size(); i++) {
            print_single(v[i]);
            if(i < (int)v.size() - 1) cout << ' ';
        }
    }
    template <class T> void print_single(const set<T> &s) {
        for(auto it = s.begin(); it != s.end(); it++) {
            print_single(*it);
            if(next(it) != s.end()) cout << ' ';
        }
    }
    template <class T> void print_single(const deque<T> &v) {
        for(int i = 0; i < (int)v.size(); i++) {
            print_single(v[i]);
            if(i < (int)v.size() - 1) cout << ' ';
        }
    }
    template <class T> void print_single(queue<T> q) {
        while(!q.empty()) {
            print_single(q.front());
            if((int)q.size() > 1) cout << ' ';
            q.pop();
        }
    }

    void print() { cout << '\n'; }
    template <class Head, class... Tail>
    void print(const Head &h, const Tail &...t) {
        print_single(h);
        if(sizeof...(Tail)) print_single(' ');
        print(t...);
    }

    // input
    template <class T, enable_if_t<is_integral<T>::value, int> = 0>
    void input_single(T &t) {
        cin >> t;
    }
    template <class T, enable_if_t<is_floating_point<T>::value, int> = 0>
    void input_single(T &t) {
        cin >> t;
    }
    template <class T, typename enable_if<has_val<T>::value>::type * = nullptr>
    void input_single(T &t) {
        cin >> t;
    }
    void input_single(__int128_t &n) {
        string s;
        cin >> s;
        if(s == "0") {
            n = 0;
            return;
        }
        bool is_minus = false;
        if(s[0] == '-') {
            s = s.substr(1);
            is_minus = true;
        }
        n = 0;
        for(int i = 0; i < (int)s.size(); i++) n = n * 10 + (int)(s[i] - '0');
        if(is_minus) n = -n;
    }
    void input_single(string &s) { cin >> s; }
    template <class T1, class T2> void input_single(pair<T1, T2> &p) {
        input_single(p.first);
        input_single(p.second);
    }
    template <class T> void input_single(vector<T> &v) {
        for(auto &e : v) input_single(e);
    }
    void input() {}
    template <class Head, class... Tail> void input(Head &h, Tail &...t) {
        input_single(h);
        input(t...);
    }
}; // namespace siro53_io
#ifdef DEBUG
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debug_print(__VA_ARGS__)
#else
#define debug(...) (void(0))
#endif
// io setup
struct Setup {
    Setup() {
        cin.tie(0);
        ios::sync_with_stdio(false);
        cout << fixed << setprecision(15);
    }
} __Setup;
using namespace siro53_io;
// types
using ll = long long;
using i128 = __int128_t;
// input macros
#define INT(...)                                                               \
    int __VA_ARGS__;                                                           \
    input(__VA_ARGS__)
#define LL(...)                                                                \
    ll __VA_ARGS__;                                                            \
    input(__VA_ARGS__)
#define STRING(...)                                                            \
    string __VA_ARGS__;                                                        \
    input(__VA_ARGS__)
#define CHAR(...)                                                              \
    char __VA_ARGS__;                                                          \
    input(__VA_ARGS__)
#define DBL(...)                                                               \
    double __VA_ARGS__;                                                        \
    input(__VA_ARGS__)
#define LD(...)                                                                \
    long double __VA_ARGS__;                                                   \
    input(__VA_ARGS__)
#define UINT(...)                                                              \
    unsigned int __VA_ARGS__;                                                  \
    input(__VA_ARGS__)
#define ULL(...)                                                               \
    unsigned long long __VA_ARGS__;                                            \
    input(__VA_ARGS__)
#define VEC(name, type, len)                                                   \
    vector<type> name(len);                                                    \
    input(name);
#define VEC2(name, type, len1, len2)                                           \
    vector name(len1, vector<type>(len2));                                     \
    input(name);
// other macros
// https://trap.jp/post/1224/
#define OVERLOAD3(_1, _2, _3, name, ...) name
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
#define REP1(i, n) for(int i = 0; i < int(n); i++)
#define REP2(i, a, b) for(int i = (a); i < int(b); i++)
#define REP(...) OVERLOAD3(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)
#define SORT(v) sort(ALL(v))
#define RSORT(v) sort(RALL(v))
#define UNIQUE(v)                                                              \
    sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end()), v.shrink_to_fit()
#define REV(v) reverse(ALL(v))
#define SZ(v) ((int)(v).size())
#define MIN(v) (*min_element(ALL(v)))
#define MAX(v) (*max_element(ALL(v)))
// util const
const int INF = 1 << 30;
const ll LLINF = 1LL << 60;
constexpr int MOD = 1000000007;
constexpr int MOD2 = 998244353;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
// util functions
void Case(int i) { cout << "Case #" << i << ": "; }
int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
template <class T> inline bool chmax(T &a, T b) {
    return (a < b ? a = b, true : false);
}
template <class T> inline bool chmin(T &a, T b) {
    return (a > b ? a = b, true : false);
}
template <class T, int dim>
auto make_vector_impl(vector<int>& sizes, const T &e) {
    if constexpr(dim == 1) {
        return vector(sizes[0], e);
    } else {
        int n = sizes[dim - 1];
        sizes.pop_back();
        return vector(n, make_vector_impl<T, dim - 1>(sizes, e));
    }
}
template <class T, int dim>
auto make_vector(const int (&sizes)[dim], const T &e = T()) {
    vector<int> s(dim);
    for(int i = 0; i < dim; i++) s[i] = sizes[dim - i - 1];
    return make_vector_impl<T, dim>(s, e);
}
vector<int> iota_gen(int n, int start = 0) {
    vector<int> ord(n);
    iota(ord.begin(), ord.end(), start);
    return ord;
}
template<typename T>
vector<int> ord_sort(const vector<T>& v, bool greater = false) {
    auto ord = iota_gen((int)v.size());
    sort(ALL(ord), [&](int i, int j) {
        if(greater) return v[i] > v[j];
        return v[i] < v[j];
    });
    return ord;
}
// #endregion Macros
#line 2 "data-structure/slope-trick.hpp"

#line 11 "data-structure/slope-trick.hpp"

// ref: https://maspypy.com/slope-trick-1-%E8%A7%A3%E8%AA%AC%E7%B7%A8
template <typename T> struct SlopeTrick {
    const T inf = std::numeric_limits<T>::max() / 3;

    T min_f, add_L, add_R;
    std::priority_queue<T> L;
    std::priority_queue<T, std::vector<T>, std::greater<T>> R;

  private:
    void push_L(T a) { L.push(a - add_L); }
    T top_L() const {
        if(L.empty()) return -inf;
        return L.top() + add_L;
    }
    T pop_L() {
        T ret = top_L();
        if(!L.empty()) L.pop();
        return ret;
    }
    void push_R(T a) { R.push(a - add_R); }
    T top_R() const {
        if(R.empty()) return inf;
        return R.top() + add_R;
    }
    T pop_R() {
        T ret = top_R();
        if(!R.empty()) R.pop();
        return ret;
    }

  public:
    SlopeTrick() : min_f(0), add_L(0), add_R(0) {}
    T get_min() const { return min_f; }
    std::tuple<T, T, T> get_min_lr() const { return {min_f, top_L(), top_R()}; }
    // 定数関数 f(x) = a を追加
    void add_const(T a) { min_f += a; }
    // f(x) = (x - a)+ を追加
    void add_right(T a) {
        min_f += std::max(top_L() - a, T(0));
        push_L(a);
        T t = pop_L();
        push_R(t);
    }
    // f(x) = (a - x)+ を追加
    void add_left(T a) {
        min_f += std::max(a - top_R(), T(0));
        push_R(a);
        T t = pop_R();
        push_L(t);
    }
    // f(x) = |x - a| = (x - a)+ + (a - x)+ を追加
    void add_abs(T a) {
        add_left(a);
        add_right(a);
    }
    // (左側)累積min
    // g(x) := min_{y <= x} f(y) なる g に変更
    void clear_right() {
        while(!R.empty()) R.pop();
    }
    // (右側)累積min
    // g(x) := min_{y >= x} f(y) なる g に変更
    void clear_left() {
        while(!L.empty()) L.pop();
    }
    // スライド最小値関数
    // g(x) := min_{x - b <= y <= x - a} f(y) (a <= b) なる g に変更
    void shift(T a, T b) {
        assert(a <= b);
        add_L += a;
        add_R += b;
    }
    // 平行移動
    // g(x) := f(x - a) なる g に変更
    void shift(T a) { shift(a, a); }
    size_t size() const { return L.size() + R.size(); }
    void swap(SlopeTrick& rhs) {
        std::swap(min_f, rhs.min_f);
        std::swap(add_L, rhs.add_L);
        std::swap(add_R, rhs.add_R);
        std::swap(L, rhs.L);
        std::swap(R, rhs.R);
    }
    void merge(SlopeTrick& rhs) {
        if(size() < rhs.size()) swap(rhs);
        while(!rhs.L.empty()) add_left(rhs.pop_L());
        while(!rhs.R.empty()) add_right(rhs.pop_R());
        min_f += rhs.min_f;
    }
    // L, R は空になる
    T eval(T x) {
        T ret = min_f;
        while(!L.empty()) ret += std::max(T(0), pop_L() - x);
        while(!R.empty()) ret += std::max(T(0), x - pop_R());
        return ret;
    }
};
#line 4 "test/mytest/data-structure/slope-trick.test.cpp"


using Slope = SlopeTrick<ll>;
ll evaluate(Slope s, ll x) {
    ll value = s.eval(x);
    assert(s.size() == 0 && s.L.empty() && s.R.empty());
    return value;
}
int main() {
    Slope zero;
    assert(zero.size() == 0 && zero.min_f == 0 && zero.add_L == 0 && zero.add_R == 0);
    assert(zero.get_min_lr() == make_tuple(0LL, -zero.inf, zero.inf));
    mt19937 rng(62);
    for(int trial = 0; trial < 100; ++trial) {
        Slope base;
        vector<pair<int, int>> terms;
        ll constant = int(rng() % 21) - 10;
        base.add_const(constant);
        for(int i = 0; i < 10; ++i) {
            int kind = rng() % 3, a = int(rng() % 21) - 10;
            terms.emplace_back(kind, a);
            if(kind == 0) base.add_left(a);
            if(kind == 1) base.add_right(a);
            if(kind == 2) base.add_abs(a);
        }
        auto f = [&](ll x) {
            ll value = constant;
            for(auto [kind, a] : terms) {
                if(kind == 0) value += max(0LL, a - x);
                if(kind == 1) value += max(0LL, x - a);
                if(kind == 2) value += abs(x - a);
            }
            return value;
        };
        ll minimum = LLONG_MAX;
        for(int x = -50; x <= 50; ++x) minimum = min(minimum, f(x));
        const auto& view = base;
        auto [value, l, r] = view.get_min_lr();
        assert(view.get_min() == minimum && value == minimum && l <= r);
        for(int x = -30; x <= 30; ++x) {
            assert(evaluate(base, x) == f(x));
            assert((l <= x && x <= r) == (f(x) == minimum));
        }
        auto left = base, right = base, shifted = base, window = base;
        left.clear_right(); right.clear_left(); shifted.shift(-3); window.shift(-2, 4);
        for(int x = -30; x <= 30; ++x) {
            ll a = LLONG_MAX, b = LLONG_MAX, c = LLONG_MAX;
            for(int y = -50; y <= x; ++y) a = min(a, f(y));
            for(int y = x; y <= 50; ++y) b = min(b, f(y));
            for(int y = x - 4; y <= x + 2; ++y) c = min(c, f(y));
            assert(evaluate(left, x) == a && evaluate(right, x) == b);
            assert(evaluate(shifted, x) == f(x + 3) && evaluate(window, x) == c);
        }
        for(bool swap_sizes : {false, true}) {
            auto a = base; Slope b; b.add_abs(3); b.add_const(7);
            if(swap_sizes) a.swap(b);
            a.merge(b);
            assert(b.size() == 0);
            for(int x = -30; x <= 30; ++x) assert(evaluate(a, x) == f(x) + abs(x - 3) + 7);
        }
    }
    INT(a, b); print(a + b);
}
Back to top page