/ SeriousOJ /

Record Detail

Runtime Error


  
# Status Time Cost Memory Cost
#1 Accepted 3ms 2.77 MiB
#2 Runtime Error free(): invalid pointer 3ms 2.785 MiB
#3 Runtime Error free(): invalid pointer 3ms 2.773 MiB

Code

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

const int N = 1e5+2;
const ll inf = 1e16;

int a[N],n,k;
ll dp[N][105],ans;
vector<int> g[N];
multiset<ll,greater<ll>> v[105];

void dfs(int u,int p=0) {
    dp[u][1] = a[u];
    int ch = 0;
    for(auto x: g[u]) {
        if(x == p) continue;
        dfs(x,u);
        ch++;
        for(int i = 0; i <= k; i++) {
            v[i].insert(dp[x][i]);
        }
        for(int i = 1; i < k; i++) {
            dp[u][i+1] = max(dp[u][i+1],dp[x][i]+a[u]);
        }
    }
    ans = max(ans, dp[u][k]);
    if(ch <= 1) return;
    for(auto x: g[u]) {
        if(x == p) continue;
        for(int j = 0; j < k; j++) {
            v[k - 1 - j].erase(v[k - 1 - j].find(dp[x][k - 1 - j]));
            ll mx = *v[k - 1 - j].begin();
            ll now = dp[x][j] + mx + a[u];
            ans = max(ans, now);
            v[k - 1 - j].insert(dp[x][k - 1 - j]);
        }
    }
    for(int i = 0; i <= k; i++) {
        v[i].clear();
    }
}
void solve() {
    cin >> n >> k;
    for(int i = 1; i <= n; i++)
        cin >> a[i];
    for(int i = 1; i < n; i++) {
        int u,v;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= k; j++) {
            dp[i][j] = -inf;
        }
    }
    dfs(1);
    cout << ans << '\n';
    return;
}

int32_t main() {
    ios_base::sync_with_stdio(false);cin.tie(NULL);
    int tc = 1;
    // cin >> tc;
    for(int kase = 1; kase <= tc; kase++) {
        //cout << "Case " << kase << ": ";
        solve();
    }
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1161 Max path sum (Hard Version)
Contest
Brain Booster #8
Language
C++17 (G++ 13.2.0)
Submit At
2025-02-17 16:17:40
Judged At
2025-02-17 16:17:40
Judged By
Score
2
Total Time
3ms
Peak Memory
2.785 MiB