Cod sursa(job #1794210)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 1 noiembrie 2016 08:22:49
Problema Avioane Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.94 kb
#include <bits/stdc++.h>

using namespace std;

const int inf = INT_MAX;
const int nmax = 1e5 + 10;

struct linear_function {
    int val;
    int a, b;

    linear_function(int V = 0, int x = 0, int y = 0) {
        val = V; a = x; b = y;
    }

    bool operator < (linear_function other) const {
        if (a == other.a) return b < other.b;
        return a < other.a;
    }

    double ix(linear_function other) {
        if (a == other.a) return -inf;
        return 1.0 * (other.b - b) / (a - other.a);
    }

    long long get_y(int x) {
        return 1LL * a * x + b;
    }
};

linear_function func[nmax];

int n;
int v[nmax];

double first[nmax];
vector < int > st;

void read_input() {
    freopen("avioane.in","r",stdin);

    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &v[i]);

    sort(v + 1, v + n + 1);

    for (int i = 1; i <= n; ++i)
        func[i] = linear_function(v[i], v[i], -v[i] * i);
}

void compute_stack() {
    for (int i = 1; i <= n; ++i) {
        while ((int)st.size() && func[i].ix(func[st.back()]) <= first[(int)st.size()-1])
            st.pop_back();

        if ((int)st.size())
            first[(int)st.size()] = func[i].ix(func[st.back()]);
        else first[(int)st.size()] = -inf;

        st.push_back(i);
    }
}

void update(long long &ans, int i, int &it) {
    if (st.empty()) {
        ans = max(ans, 1LL * func[i].val * (n - i + 1));
        return;
    }

    while (it < (int)st.size() - 2 && first[it+1] <= i)
        it++;

    ans = max(ans, func[st[it]].get_y(i) + 1LL * func[i].val * (n - i + 1));
}

void get_ans() {
    freopen("avioane.out","w",stdout);

    long long ans = -1; int it = 0;
    for (int i = 1; i <= n; ++i)
        update(ans, i, it);

    printf("%lld\n", ans);
}

void solve() {
    compute_stack();
    get_ans();
}

int main()
{
    read_input();
    solve();

    return 0;
}