DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

CHOICE

Back to problem

Editorial

Use a DFS Euler tour to represent every subtree of a vertex xxx as an interval [inx,outx][in_x,out_x][inx​,outx​].

Let uuu be Woohyeon's current vertex, and maintain d(v)=dist(u,v)d(v)=\mathrm{dist}(u,v)d(v)=dist(u,v) for every vertex vvv. If Woohyeon moves from uuu to an adjacent vertex along an edge of length , distances to vertices on the side of that edge decrease by , while distances to vertices on the side increase by .

If xxx is a child of uuu, add www to every distance, then subtract 2w2w2w from the subtree of xxx. If xxx is the parent of , subtract from every distance, then add to the subtree of .

Build a lazy segment tree whose nodes store two minima: the minimum distance to a selected vertex and the minimum distance to a not-selected vertex. A range addition shifts both minima. A range state flip swaps the two minima. Both updates can be performed by lazy propagation. For a type-333 query, read the minimum for selected vertices at the segment-tree root, or return −1-1−1 if none exists.

Preprocessing takes O(N)O(N)O(N) time. Every query takes O(log⁡N)O(\log N)O(logN) time, with O(N)O(N)O(N) memory. Use 64-bit integers for distances and updates.

xxx
www
xxx
www
uuu
www
uu
u
www
2w2w2w
uuu