This page is still under construction.

Parts of this page are still being built. What you see may change.

Nearby Cows

Interview

Time limit1sMemory limit128 MB

Summary
On a tree of N fields with C(i) cows at each field, report for every field the total cows within distance K, where K is at most 20.
Level

Medium6 of 10

Topics
Tree, DFS, Dynamic programming, Prefix sum
Solved
No attempts yet

Problem

Farmer John has noticed that his cows often wander between nearby fields. To be ready for this, he wants every field to grow enough grass not only for the cows that start there, but also for the cows that might arrive from fields close by.

The farm has NN fields (1≤N≤100,0001 \le N \le 100{,}000) connected by N−1N-1 bidirectional trails. Between any two fields there is exactly one path made of trails, so the fields form a tree. Field ii starts with C(i)C(i) cows (0≤C(i)≤10000 \le C(i) \le 1000), and a cow may wander to another field by crossing at most KK trails (1≤K≤201 \le K \le 20).

For every field ii, Farmer John wants to know M(i)M(i): the largest number of cows that could gather there. This equals the sum of C(j)C(j) over all fields jj whose distance from ii (the number of trails on the unique path between them) is at most KK. Given the layout of the farm and every C(i)C(i), compute M(i)M(i) for all fields.

Input

  • Line 1: two space-separated integers NN and KK.
  • Lines 2 to NN: each line has two space-separated integers ii and jj (1≤i,j≤N1 \le i, j \le N), meaning fields ii and jj are directly connected by a trail.
  • Lines N+1N+1 to 2N2N: line N+iN+i contains the integer C(i)C(i) (0≤C(i)≤10000 \le C(i) \le 1000).

Output

  • Lines 1 to NN: line ii contains M(i)M(i), the number of cows within distance KK of field ii.

Hint

In the first example there are 66 fields, with trails connecting (5,1)(5,1), (3,6)(3,6), (2,4)(2,4), (2,1)(2,1), and (3,2)(3,2), and field ii holds C(i)=iC(i) = i cows. With K=2K = 2, field 11 can be reached within two trails by fields 1,2,3,4,51, 2, 3, 4, 5, whose cows total 1+2+3+4+5=151 + 2 + 3 + 4 + 5 = 15, so M(1)=15M(1) = 15.

Examples2

  1. Example 1

    Input
    6 2
    5 1
    3 6
    2 4
    2 1
    3 2
    1
    2
    3
    4
    5
    6
    
    Expected output
    15
    21
    16
    10
    8
    11
    
  2. Example 2

    Input
    5 1
    1 2
    2 3
    3 4
    4 5
    10
    20
    30
    40
    50
    
    Expected output
    30
    60
    90
    120
    90