제출 #930230

#제출 시각아이디문제언어결과실행 시간메모리
930230RegulusChase (CEOI17_chase)C++17
100 / 100
287 ms345724 KiB
#include <bits/stdc++.h>                // chase_ceoi17
#define IO ios::sync_with_stdio(false);cin.tie(0);
#define debug(x) cerr << #x << " = " << (x) << ' '
#define bug(x) cerr << (x) << ' '
#define endl cerr << '\n'
#define all(v) (v).begin(), (v).end()
#define SZ(v) (ll)(v).size()
#define lowbit(x) (x)&-(x)
#define pb emplace_back
#define F first
#define S second
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;

//#define TEST

const int N = 1e5+5;
const ll LLINF = 2e18;
int m, a[N];
ll sum[N], ans, dp[N][2][105], dp2[N][2][105];
vector<int> g[N];

inline bool chk(ll n) { return n > ans; }

inline void dfs(int x, int fa)
{
    for (int v : g[x]) sum[x] += a[v];

    dp[x][1][0] = dp2[x][1][0] = -LLINF;
    //dp[x][1][i] = dp2[x][1][i] = sum[x];
    for (int i=1; i <= m; ++i) dp[x][1][i] = dp2[x][1][i] = sum[x];
    for (int v : g[x])
    {
        if (v == fa) continue;
        dfs(v, x);
        
        for (int i=1; i < m; ++i)
        {
            ans = max(ans,
                max(dp[x][0][m-i], dp[x][1][m-i]) + max(dp2[v][0][i], dp2[v][1][i]-a[x]));
            ans = max(ans,
                max(dp2[x][0][m-i], dp2[x][1][m-i]-a[v]) + max(dp[v][0][i], dp[v][1][i]));
            //ans = max(ans, max(dp[x][0][m-i], dp[x][1][m-i]) + dp2[v][t][i] - a[x]);
            //ans = max(ans, max(dp2[x][0][m-i], dp2[x][1][m-i]) + dp[v][t][i]);
        }
        //debug(x), debug(v), debug(ans), endl;

        for (int i=1; i <= m; ++i)
        {
            dp[x][0][i] = max({dp[x][0][i], dp[v][0][i], dp[v][1][i]});
            dp2[x][0][i] = max({dp2[x][0][i], dp2[v][0][i], dp2[v][1][i] - a[x]});
            dp[x][1][i] = max(dp[x][1][i], max(dp[v][0][i-1], dp[v][1][i-1]) + sum[x] - a[v]);
            dp2[x][1][i] = max(dp2[x][1][i], max(dp2[v][0][i-1], dp2[v][1][i-1] - a[x]) + sum[x]);
        }
        ans = max({ans, dp[x][1][m], dp2[x][1][m]});
    }

    #ifdef TEST
    debug(x), debug(sum[x]), debug(ans), endl;
    for (int t=0; t < 2; ++t)
    {
        for (int i=0; i <= m; ++i) bug(dp[x][t][i]); endl;
        for (int i=0; i <= m; ++i) bug(dp2[x][t][i]); endl;
    } endl;
    #endif
}

int main(void)
{ IO
    int n, i;

    cin >> n >> m;
    for (i=1; i <= n; ++i) cin >> a[i];
    for (i=0; i < n-1; ++i)
    {
        int x, y; cin >> x >> y;
        g[x].pb(y), g[y].pb(x);
    }

    dfs(1, 0);
    cout << ans << '\n';


    return 0;
}

/*
*/
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...