Nearby Cows
InterviewTime limit1sMemory limit128 MB
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 fields () connected by bidirectional trails. Between any two fields there is exactly one path made of trails, so the fields form a tree. Field starts with cows (), and a cow may wander to another field by crossing at most trails ().
For every field , Farmer John wants to know : the largest number of cows that could gather there. This equals the sum of over all fields whose distance from (the number of trails on the unique path between them) is at most . Given the layout of the farm and every , compute for all fields.
Input
- Line 1: two space-separated integers and .
- Lines 2 to : each line has two space-separated integers and (), meaning fields and are directly connected by a trail.
- Lines to : line contains the integer ().
Output
- Lines 1 to : line contains , the number of cows within distance of field .
Hint
In the first example there are fields, with trails connecting , , , , and , and field holds cows. With , field can be reached within two trails by fields , whose cows total , so .