题解:P8677 [蓝桥杯 2018 国 A] 采油

· · 题解

#include <bits/stdc++.h>
using namespace std;
#define int long long

#ifdef __linux__
#define gc getchar_unlocked
#define pc putchar_unlocked
#else
#define gc getchar
#define pc putchar
#endif

namespace IO {
    char ch;
    int read() {
        int x = 0, f = 1;
        ch = gc();
        while (!isdigit(ch)) {
            if (ch == '-') f = -1;
            ch = gc();
        }
        while (isdigit(ch)) {
            x = x * 10 + (ch ^ 48);
            ch = gc();
        }
        return x * f;
    }

    template<typename... Args>
    void read(Args &... args) {
        ((args = read()), ...);
    }

    void out(int x) {
        if (x < 0) pc('-'), x = -x;
        if (x < 10) pc(x + '0');
        else out(x / 10), pc(x % 10 + '0');
    }

    template<typename... Args>
    void out(Args... args) {
        ((out(args), pc(' ')), ...);
        pc('\n');
    }
}

using IO::read;
using IO::out;

constexpr int maxn = 1e5 + 10;
struct Node {
    int b, s, c;
};

int n;
Node a[maxn];
vector<pair<int,int>> gra[maxn];
int total_edge_w = 0;

void dfs(int u, int fa) {

    vector<Node> items;
    items.push_back(a[u]);

    for (auto [v,w] : gra[u]) {
        if (v == fa) continue;
        dfs(v, u);
        items.push_back(a[v]);
    }


    if (items.size() == 1) return;


    sort(items.begin(), items.end(), [](const Node &x, const Node &y){
        if (x.c != y.c) return x.c > y.c;
        return x.b > y.b;
    });


    int ansb = 0;
    int nc = 0;
    long long sum_b_minus_c = 0;
    for (auto &nd : items) {
        sum_b_minus_c += (nd.b - nd.c);
        if (nc < nd.b) {
            ansb += (nd.b - nc);
            nc = nd.c;
        } else {
            nc -= (nd.b - nd.c);
        }
    }
    int ansc = ansb - sum_b_minus_c;


    a[u].b = ansb;
    a[u].c = ansc;
}

void solve() {
    n = read();
    for (int i = 1; i <= n; ++i) {
        a[i].b = read();
    }
    for (int i = 1; i <= n; ++i) {
        a[i].s = read();
        a[i].c = max(a[i].b - a[i].s, 0LL);
        a[i].b = max(a[i].b, a[i].s);
    }

    int root = 1;
    int maxc = -1;
    for (int i = 1; i <= n; ++i) {
        if (a[i].c > maxc) {
            maxc = a[i].c;
            root = i;
        }
    }


    for (int i = 2; i <= n; ++i) {
        int v = read(), w = read();
        gra[i].emplace_back(v, w);
        gra[v].emplace_back(i, w);
        total_edge_w += w;
    }

    dfs(root, 0);

    out(total_edge_w * 2, a[root].b);
}

signed main() {
    solve();
    return 0;
}