Submission #1123754

#TimeUsernameProblemLanguageResultExecution timeMemory
1123754math_rabbit_1028Tree (IOI24_tree)C++20
10 / 100
2095 ms28832 KiB
#include "tree.h"
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;

int n;
int par[202020];
vector<int> child[202020];
ll w[202020];

bool compare(int a, int b) {
    return w[a] < w[b];
}

void init(vector<int> P, vector<int> W) {
    n = (int)P.size();
    for (int i = 0; i < n; i++) {
        par[i] = P[i];
        child[par[i]].push_back(i);
    }
    for (int i = 0; i < n; i++) w[i] = W[i];
    for (int i = 0; i < n; i++) {
        sort(child[i].begin(), child[i].end(), compare);
    }
}

ll dp[202020], sum[202020];

ll minabs(ll l, ll r) {
    if (l <= 0 && r >= 0) return 0;
    if (r < 0) return r;
    if (l > 0) return l;
}

void solve(int v, ll L, ll R) {
    for (int u : child[v]) {
        solve(u, L, R);
        dp[v] += dp[u];
        sum[v] += sum[u];
    }
    ll now = minabs(L - sum[v], R - sum[v]);
    if (now < 0) {
        for (int u : child[v]) {
            if (w[u] >= w[v]) break;
            if (-now > sum[u]-L) {
                dp[u] += (sum[u]-L) * w[u];
                dp[v] += (sum[u]-L) * w[u];
                sum[u] = L;
                sum[v] -= sum[u]-L;
                now += sum[u]-L;
            }
            else {
                dp[u] += (-now) * w[u];
                dp[v] += (-now) * w[u];
                sum[u] -= now;
                sum[v] += now;
                now = 0;
            }
        }
    }
    else if (now > 0) {
        for (int u : child[v]) {
            if (w[u] >= w[v]) break;
            if (now > R-sum[u]) {
                dp[u] += (R-sum[u]) * w[u];
                dp[v] += (R-sum[u]) * w[u];
                sum[u] = R;
                sum[v] += R-sum[u];
                now -= R-sum[u];
            }
            else {
                dp[u] += (now) * w[u];
                dp[v] += (now) * w[u];
                sum[u] += now;
                sum[v] += now;
                now = 0;
            }
        }
    }
    sum[v] += now;
    dp[v] += abs(now) * w[v];
}

long long query(int L, int R) {
    for (int i = 0; i < n; i++) sum[i] = dp[i] = 0;
    solve(0, L, R);
    return dp[0];
}

Compilation message (stderr)

tree.cpp: In function 'll minabs(ll, ll)':
tree.cpp:33:1: warning: control reaches end of non-void function [-Wreturn-type]
   33 | }
      | ^
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...