hi anyone pls can help i m getting tle in a java solution pls can anyone help

this is the atcoder contest link: D - Play Train

submission link: Submission #26955824 - UNICORN Programming Contest 2021(AtCoder Beginner Contest 225)

If anybody could help please help me out as for printing i have proceeded with naive approach and my total time complexity O(no of elements connected*No of queries) total time complexity if any one can help pls help me out

pls help me out