EAGLE1 - Eagle and Dogs

Eagle (AKA Mohamed Ahmed) lives in a city consists of n intersections connected by n-1 roads, in a way that can go from any intersection to any other intersection moving along some of these roads.

Every day he starts walking in the city following a simple strategy; if he's at some intersection he has to pick one of the roads connected to it at random such that he hasn't walked through it before and walk through it and and if there isn't any, he stops and goes home.

His only problem is that he's afraid of dogs. He doesn't even like seeing dogs. So he's wondering in the worst scenario, how many dogs he'll have to see during his walk until he stops if he starts walking at some intersection. Can you help him?


The input starts with an integer T (1 <= T <= 10), the number of test cases. following T blocks describing each test case.

Each block starts with a line containing an integer n (2 <= n <= 105), the number of intersections in the city. Intersections are numbers 1 through n.

Followed by n-1 lines each containing integers u, v, (1 <= u, v <= n) and d (1 <= d <= 109), the numbers of intersections at the end of this road and the number od dogs Eagle will see walking in this road.


For each test case print a line containing n integers, the ith integer represents the maximum number of dogs Eagle might see if he starts his walk at intersection i.


1 2 3
3 2 4
3 4 5
12 9 7 12

hide comments
princemishra: 2021-06-26 07:23:04

dp on trees question
example test case:

1 2 3
1 3 5
2 4 15
4 5 120
3 6 12

138 135 143 120 155 155

cryp_bipul17: 2021-05-11 07:41:23

I am trying to run two dfs one from the beginning and another from end and counting the number of dogs in each node and finding the maximum of the two dfs but getting WA can anyone please tell is my approach correct

sshubham_26: 2021-04-28 17:05:09

i have called dfs two times only

vishal998452: 2021-04-07 08:41:22

AC in two Go:) but important point is
1.answer is not fit in int so use long long
2.max dfs call is 2 .if u use more than two dfs call it give tle.

rushi2001: 2021-04-06 19:40:25

My approach : I Just applied dfs from two ends of graph
but getting wrong ans plz help
what should i do

Last edit: 2021-04-06 19:41:05
sonukumar: 2021-01-25 21:37:01

try with a single dfs run
don't go for multiple dfs. it will lead to TLE

lm10_piyush: 2021-01-10 16:44:58

Use DP.

ks1999: 2020-09-26 20:15:00

@eagle93: can there be cycles?

Last edit: 2020-09-26 21:52:16
kauai68: 2020-05-09 11:10:01

dfs is not a problem, but how often do you call dfs?

saifedin6: 2019-10-02 09:16:18

why did I get time limit exceeded ?! I did only use dfs..

Added by:eagle93
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64 JS-MONKEY