#include "bits/stdc++.h"
using namespace std;
#define endl '\n'
#define debug(x) cerr << #x << " == " << (x) << '\n';
#define all(x) begin(x), end(x)
using ll = long long;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
template<typename T>
void chmin(T& x, T y) { x = min(x, y); }
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int N, M;
cin >> N >> M;
vector<int> D(N);
for (auto& x : D) cin >> x;
vector<vector<int>> E(N);
for (int i = 0; i < N - 1; ++i) {
int u, v;
cin >> u >> v;
--u, --v;
E[u].push_back(v), E[v].push_back(u);
}
vector<bool> vis(N, false);
auto dfs = [&](auto&& self, int u, int p) -> vector<array<ll, 2>> {
vis[u] = true;
vector<array<ll, 2>> dp = {{0LL, LINF}, {LINF, LINF}};
for (auto v : E[u]) if (v != p) {
auto dpv = self(self, v, u);
int k = (int)size(dp), l = (int)size(dpv);
vector<array<ll, 2>> dpnxt(k + l - 1, {LINF, LINF});
int add[4] = {D[u] + D[v], D[v], D[u], 0};
int b[4] = {2, 1, 1, 0};
for (int i = 0; i < k; ++i) {
for (int j = 0; j < l; ++j) {
for (int mask = 0; mask < 4; ++mask) {
int s = mask & 1, t = mask >> 1 & 1;
chmin(dpnxt[i + j][s], dp[i][s] + dpv[j][t]);
if (i + j + b[mask] < k + l - 1) {
chmin(dpnxt[i + j + b[mask]][1], dp[i][s] + dpv[j][t] + add[mask]);
}
}
}
}
swap(dp, dpnxt);
}
return dp;
};
vector<ll> dp(1, 0);
for (int u = 0; u < N; ++u) {
if (vis[u]) continue;
auto comp = dfs(dfs, u, -1);
int k = (int)size(dp), l = (int)size(comp);
vector<ll> dpnxt(k + l - 1, LINF), add(l, LINF);
for (int j = l - 1; j >= 0; --j) {
add[j] = min(comp[j][0], comp[j][1]);
if (j + 1 < l) add[j] = min(add[j], add[j + 1]);
}
for (int i = 0; i < k; ++i) {
for (int j = 0; j < l; ++j) {
chmin(dpnxt[i + j], dp[i] + add[j]);
}
}
swap(dp, dpnxt);
}
assert(is_sorted(all(dp)));
int Q;
cin >> Q;
for (int z = 0; z < Q; ++z) {
ll S;
cin >> S;
int ans = (int)distance(begin(dp), upper_bound(all(dp), S)) - 1;
cout << ans << endl;
}
exit(0);
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
15 ms |
624 KB |
Output is correct |
2 |
Correct |
19 ms |
656 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
15 ms |
624 KB |
Output is correct |
2 |
Correct |
19 ms |
656 KB |
Output is correct |
3 |
Correct |
56 ms |
1704 KB |
Output is correct |
4 |
Correct |
59 ms |
1732 KB |
Output is correct |
5 |
Correct |
57 ms |
1220 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
40 ms |
1356 KB |
Output is correct |
2 |
Runtime error |
1 ms |
476 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
15 ms |
624 KB |
Output is correct |
2 |
Correct |
19 ms |
656 KB |
Output is correct |
3 |
Correct |
56 ms |
1704 KB |
Output is correct |
4 |
Correct |
59 ms |
1732 KB |
Output is correct |
5 |
Correct |
57 ms |
1220 KB |
Output is correct |
6 |
Correct |
40 ms |
1356 KB |
Output is correct |
7 |
Runtime error |
1 ms |
476 KB |
Execution killed with signal 11 |
8 |
Halted |
0 ms |
0 KB |
- |