Cod sursa(job #1988317)

Utilizator retrogradLucian Bicsi retrograd Data 2 iunie 2017 17:42:43
Problema Euro Scor 25
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.6 kb
#include <vector>
#include <iostream>
#include <queue>
#include <set>
#include <cassert>
#include <limits>
#include <algorithm>
#include <map>

using namespace std;


class ConvexSet {
    using T = long long;

    struct SetElem {
        T a, b;
        mutable T ans;

        bool is_query;

        SetElem(T query_x) : b(query_x), ans(numeric_limits<T>::min()), is_query(true) {}
        SetElem(T a, T b) : a(a), b(b), is_query(false) {}

        T eval(T x) const {
            return a * x + b;
        }

        bool operator< (const SetElem &rhs) const {
            assert(!is_query);
            if (rhs.is_query) {
                // Upper bound operates from right to left
                T now = eval(rhs.b);
                if (rhs.ans < now) {
                    rhs.ans = now;
                    return true;
                }
                return false;
            } else return (a != rhs.a) ? a < rhs.a : b > rhs.b;
        }
    };

    set<SetElem> data;

    bool is_bad(set<SetElem>::iterator it) {
        if (it == data.begin() || next(it) == data.end())
            return false;

        auto prv = prev(it), nxt = next(it);
        return (it->b - prv->b) * (nxt->a - it->a)
            >= (it->b - nxt->b) * (prv->a - it->a);
    }

public:
    void Insert(T slope, T intercept) {
        auto it = data.insert(SetElem(slope, intercept)).first;

        if (is_bad(it)) data.erase(it);
        else {
            while (it != data.begin()) {
                auto prv = prev(it);
                if (is_bad(prv)) {
                    data.erase(prv);
                } else break;
            }
            while (next(it) != data.end()) {
                auto nxt = next(it);
                if (is_bad(nxt)) {
                    data.erase(nxt);
                } else break;
            }
        }
    }

    T EvaluateMax(T x) {
        SetElem ret(x);
        data.lower_bound(ret);
        return ret.ans;
    }
};
 

int main() {
    freopen("euro.in", "r", stdin);
    freopen("euro.out", "w", stdout);
    
    int n, t;
    cin >> n >> t;

    // dp[i] = max_j(dp[j] + (gain[i] - gain[j]) * i - t)
    // dp[i] = max_j(dp[j] - gain[j] * i + gain[i] * i - t)
    // dp[i] = gain[i] * i - t + max_j(dp[j] - gain[j] * i)
    // solution: keep stack of linear functions of type -gain[j] * X + dp[j]
    // no monotony -> need set

    ConvexSet fun_set;
    fun_set.Insert(0, 0);

    long long ans = 0, gain = 0;
    for (int i = 1; i <= n; ++i) {
        int x; cin >> x; gain += x;
        ans = fun_set.EvaluateMax(i) + gain * i - t;
        fun_set.Insert(-gain, ans);
    }
    cout << ans << endl;
    return 0;
}