"Greedy" acrobat cattle

Acrobat cattle

Link to the original question: acrobat cattle

Subject to the effect

You \ (n \) cows, each cow has a weight \ (w_i \) and a strong degree \ (S_I \) , are now trying to stack up cattle, there is a risk of the value of each cow, the risk that the value of the current All the weight of the cattle cow head cow together minus the current degree of stronger, to make the maximum value of the minimum

Topic solution to a problem

Originally thought it was a dichotomous questions, but found that half and no way to deal with this only in a heap on top of treatment, then consider greedy, we found two values, you can use a similar king game idea to get, so just listed the equations \ (w_i + S_I \) , in ascending order with this equation, how the column ... because, multiply and better treatment.

How does that prove? First cattle freely exchange position of the two positions

ID Former exchange After the exchange
\(i\) \(\Sigma_{j = 1}^{i - 1}w_j - s_i\) \(\Sigma_{j = 1}^{i - 1}w_j + w_{i + 1} - s_i\)
\(i + 1\) \(\Sigma_{j = 1}^{i}w_j - s_{i + 1}\) \(\Sigma_{j = 1}^{i - 1} - s_{i + 1}\)

Then simplify available

ID Former exchange After the exchange
\(i\) \(-s_i\) \(w_{i + 1} - s_i\)
\(i + 1\) \(w_i-s_{i + 1}\) \(-s_{i + 1}\)

Because s, w are positive integers, so \ (- S_I <W_. 1} + {I - S_I \) , \ (W_i-S_ {I}. 1 +> -s_. 1} + I {\)

So now we need to compare \ (and w_i - s_ {i + 1} and w_ {i + 1} - s_i \)

If \ (W_i - S_ {I}. 1 ≤ W_ + +. 1 {I} - S_I \) , i.e. \ (w_i + s_i ≤ w_ { i + 1} + s_ {i + 1} \) before switching Optimal

If \ (> W_i - S_ {I +. 1}> W_ {I +. 1} - S_I \) , i.e. \ (> w_i + s_i> w_ {i + 1} + s_ {i + 1} \) after an exchange time optimal

So these two we just sorted in ascending order of descending This question can be resolved

code show as below

//#define fre yes

#include <cstdio>
#include <iostream>
#include <algorithm>

const int N = 50005;
struct Node {
    int w, s, sum;
} q[N];

bool cmp(Node x, Node y) {
    return x.sum < y.sum;
}

int main() {
    static int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d %d", &q[i].w, &q[i].s);
        q[i].sum = q[i].w + q[i].s;
    } std::sort(q + 1, q + 1 + n, cmp);
    long long ans = -1e18, sum;
    for (int i = 1; i <= n; i++) {
        sum -= q[i].s;
        ans = std::max(ans, sum);
        sum += q[i].sum;
    } printf("%lld\n", ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/Nicoppa/p/11525436.html