QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#287979 | #4815. Flower's Land | zzy0922 | RE | 0ms | 0kb | C++14 | 2.7kb | 2023-12-21 13:44:29 | 2023-12-21 13:44:30 |
answer
#include <bits/stdc++.h>
inline void chkmax(int &x, const int &v) {
x = std::max(x, v);
}
const int N = 40005;
int n, k;
int a[N];
std::vector<int> t[N];
bool vis[N];
int rt;
int siz[N], mn, sum;
void calc_siz(int u, int f) {
siz[u] = 1;
int msiz = 0;
for (const int &v : t[u]) {
if (v == f || vis[f]) continue;
calc_siz(v, u);
msiz = std::max(msiz, siz[v]);
siz[u] += siz[v];
}
msiz = std::max(msiz, sum - siz[u]);
if (msiz < mn) {
rt = u;
mn = msiz;
}
}
void get_rt(int u) {
sum = siz[u];
mn = n;
calc_siz(u, -1);
calc_siz(rt, -1);
}
int tot, dfn[N], rnk[N];
void get_dfn(int u, int f) {
dfn[u] = ++tot;
rnk[tot] = u;
for (const int &v : t[u]) {
if (v == f || vis[v]) continue;
get_dfn(v, u);
}
}
int f[N][3005], g[N][3005];
int ans[N];
void dfz(int u) {
tot = 0;
get_dfn(u, -1);
// memset(f, 0, sizeof f);
// memset(g, 0, sizeof g);
// std::cout << "\n\n";
// for (int i = 1; i <= tot; i++) std::cout << rnk[i] << ' ' << siz[rnk[i]] << '\n';
// std::cout << "\n\n";
for (int i = 0; i <= tot + 1; i++){
memset(f[i], 0xcf, sizeof(f[i]));
memset(g[i], 0xcf, sizeof(g[i]));
}
f[1][0] = 0;
for (int i = 1; i <= tot; i++) {
for (int j = 0; j < k; j++)
chkmax(f[i + 1][j + 1], f[i][j] + a[rnk[i]]);
for (int j = 0; j <= k; j++)
chkmax(f[i + siz[rnk[i]]][j], f[i][j]);
}
g[tot][0] = 0;
for (int i = tot - 1; i >= 1; i--) {
for (int j = 1; j <= k; j++)
chkmax(g[i][j], g[i + 1][j - 1] + a[rnk[i + 1]]);
for (int j = 0; j <= k; j++)
chkmax(g[i][j], g[i + siz[rnk[i + 1]]][j]);
}
for (int i = 1; i <= tot; i++)
for (int j = 0; j <= k - 1; j++)
chkmax(ans[rnk[i]], f[i][j] + g[i][k - 1 - j] + a[rnk[i]]);
// std::cout << u << '\n';
// for (int i = 1; i <= n; i++) std::cout << ans[i] << ' ';
// std::cout << '\n';
// exit(0);
vis[u] = 1;
for (const int &v : t[u]) {
if (vis[v]) continue;
get_rt(v);
dfz(rt);
}
}
int main() {
std::cin.tie(0)->sync_with_stdio(0);
std::cin >> n >> k;
for (int i = 1; i <= n; i++) std::cin >> a[i];
for (int i = 1, x, y; i <= n - 1; i++) {
std::cin >> x >> y;
t[x].push_back(y);
t[y].push_back(x);
}
sum = n;
mn = n;
calc_siz(1, -1);
calc_siz(rt, -1);
dfz(rt);
for (int i = 1; i <= n; i++) std::cout << ans[i] << ' ';
std::cout << '\n';
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Runtime Error
input:
5 3 6 10 4 3 4 3 4 4 2 2 5 5 1