QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#276203 | #4815. Flower's Land | GeZhiyuan | TL | 1ms | 8536kb | C++14 | 1.9kb | 2023-12-05 18:04:57 | 2023-12-05 18:04:58 |
Judging History
answer
#include<bits/stdc++.h>
using namespace std;
const int N = 4e4 + 5, K = 3000 + 5;
int n = 0, k = 0, tag[N] = {}, a[N] = {}, f[N][K] = {}, g[N][K] = {}, ans[N] = {};
int m = 0, siz[N] = {};
vector<vector<int> > G(N);
vector<int> V;
inline void dfs1(int u, int p = 0){
siz[u] = 1, m ++;
for(int v : G[u]) if(!tag[v] && v != p){
dfs1(v, u);
siz[u] += siz[v];
}
}
inline int dfs2(int u, int p = 0){
for(int v : G[u]) if(!tag[v] && v != p) if(2 * siz[v] > m) return dfs2(v, u);
return u;
}
inline void dfs3(int u, int p = 0){
siz[u] = 1, V.push_back(u);
for(int v : G[u]) if(!tag[v] && v != p){
dfs3(v, u);
siz[u] += siz[v];
}
}
inline void calc(){
for(int i = 0 ; i <= m ; i ++) memset(f[i], 0xa0, sizeof(f[i])), memset(g[i], 0xa0, sizeof(g[i]));
f[0][0] = 0, g[m][0] = 0;
for(int i = 0 ; i < m ; i ++){
int s = siz[V[i]], w = a[V[i]];
for(int x = 0 ; x <= k ; x ++){
f[i + 1][x + 1] = max(f[i + 1][x + 1], f[i][x] + w);
f[i + s][x] = max(f[i + s][x], f[i][x]);
}
}
for(int i = m - 1 ; i >= 0 ; i --){
int s = siz[V[i]], w = a[V[i]];
for(int x = 0 ; x <= k ; x ++){
g[i][x + 1] = max(g[i][x + 1], g[i + 1][x] + w);
g[i][x] = max(g[i][x], g[i + s][x]);
}
}
for(int i = 0 ; i < m ; i ++) for(int x = 0 ; x < k ; x ++) if(f[i][x] >= 0 && g[i + 1][k - 1 - x] >= 0)ans[V[i]] = max(ans[V[i]], f[i][x] + g[i + 1][k - 1 - x] + a[V[i]]);
}
inline void cdq(int r){
m = 0, dfs1(r);
if(m < k) return;
r = dfs2(r);
V.clear(), dfs3(r);
calc();
tag[r] = 1; for(int v : G[r]) cdq(v);
}
int main(){
memset(ans, 0xa0, sizeof(ans));
scanf("%d %d", &n, &k);
for(int u = 1 ; u <= n ; u ++) scanf("%d", &a[u]);
for(int i = 1, u = 0, v = 0 ; i < n ; i ++){
scanf("%d %d", &u, &v);
G[u].push_back(v), G[v].push_back(u);
}
cdq(1);
for(int u = 1 ; u <= n ; u ++) printf("%d\n", ans[u]);
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 1ms
memory: 6676kb
input:
5 3 6 10 4 3 4 3 4 4 2 2 5 5 1
output:
20 20 17 17 20
result:
ok 5 number(s): "20 20 17 17 20"
Test #2:
score: 0
Accepted
time: 1ms
memory: 6492kb
input:
7 4 1 3 2 1 7 12 17 4 6 1 4 5 1 2 5 7 6 3 2
output:
31 13 13 31 21 31 31
result:
ok 7 numbers
Test #3:
score: 0
Accepted
time: 1ms
memory: 6648kb
input:
1 1 20
output:
20
result:
ok 1 number(s): "20"
Test #4:
score: 0
Accepted
time: 0ms
memory: 8536kb
input:
10 3 19 7 25 18 93 97 21 51 60 80 6 7 7 1 1 9 9 10 10 2 2 5 5 3 3 8 8 4
output:
159 180 169 94 180 137 137 169 159 180
result:
ok 10 numbers
Test #5:
score: -100
Time Limit Exceeded
input:
20 3 932 609 248 720 831 253 418 482 1000 542 436 304 217 163 872 380 704 845 497 610 17 12 1 17 15 17 13 17 2 15 16 2 18 16 8 16 4 16 19 4 6 4 20 19 10 19 9 10 5 10 7 9 3 9 14 5 11 7