Submission #609646

#TimeUsernameProblemLanguageResultExecution timeMemory
609646AugustinasJucasFireworks (APIO16_fireworks)C++14
19 / 100
18 ms8020 KiB
#include <bits/stdc++.h>

using namespace std;
const int dydis = 3e5 + 10;
const long long inf = 1e15;
int n, m, k;
const int MX = 300;
vector<pair<int, int> > gr[dydis];

long long dp[dydis][MX+1] = {};
long long st[dydis] = {};
void dfs(int v) {
    if(gr[v].size() == 0) {
        for(auto &x : dp[v]) x = inf;
        dp[v][0] = 0;
        return ;
    }

    for(auto x : gr[v]) {
        dfs(x.first);
    }

    for(auto x : gr[v]) {
        int u = x.first; long long w = x.second;

        for(int i = 0; i <= MX; i++) st[i] = inf;


        for(int i = 0; i <= MX; i++) {
            for(int j = 0; i+j <= MX; j++) {
                st[i+j] = min(st[i+j], abs(i-w) + dp[u][j]);
            }
        }

        for(int i = 0; i <= MX; i++) {
            dp[v][i] += st[i];
        }
    }
    //cout << "dp[" << v+1 << "]:\n";
   // for(int i = 0; i <= MX; i++) {
   //     cout << i << ": " << dp[v][i] << endl;
   // }
}

int main() {
    //ifstream in("in.txt");
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    cin >> m >> k;
    n = m + k;
    for(int i = 1; i < n; i++) {
        int p, w;
        cin >> p >> w; p--;
        gr[p].push_back({i, w});
        //gr[i].push_back({p, w});
    }

    dfs(0);

    long long ans = inf;
    for(int i = 0; i <= MX; i++) {
        ans = min(ans, dp[0][i]);
    }

    cout << ans;
    return 0;
}
/*
4 6
1 5
2 5
2 8
3 3
3 2
3 3
2 9
4 4
4 3
*/
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...