Get the treats Hackerearth

Calling dfs at each node will cause TLE ,How to optimize
also Editorial is not given in Hackerearth.
Question Link-https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/practice-problems/algorithm/parwal-problem/