DOJ logoDOJ
Problems
Recently added problemsSaved problems
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

Finding Triangular Stars

Back to problem

Editorial

Fix a vertex vvv as the center. Consider each direction incident to vvv, and define the length of that direction as the maximum distance one can go from vvv through that direction.

A triangular star of size KKK centered at vvv exists if and only if there are at least three directions whose lengths are at least KKK. Therefore, the largest possible size of a triangular star centered at vvv is the third largest value among the direction lengths of vvv.

We compute this value for every vertex. Root the tree arbitrarily and perform two tree DP passes.

Let downvdown_vdownv​ be the maximum distance one can reach by going downward into the subtree of vvv. This can be computed in postorder.

Then let upvup_vupv​ be the maximum distance one can reach from vvv through the parent direction. When computing upuup_uupu​ for a child of , use the longest direction from excluding the direction toward .

For each vertex, collect the lengths downu+1down_u+1downu​+1 for every child uuu, and also upvup_vup if is not the root. The third largest collected value is denoted by . Then vertex contributes one triangular star of each size .

Using a difference array, add 111 to the range [1,Lv][1,L_v][1,Lv​] for every vertex vvv, and then take prefix sums to obtain all answers.

The time complexity is O(N)O(N)O(N), and the memory complexity is O(N)O(N)O(N).

uu
u
vvv
vvv
uuu
v
​
vvv
LvL_vLv​
vvv
1,2,…,Lv1,2,\ldots,L_v1,2,…,Lv​