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 account linking.

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

Colors and Paths

Back to problem

Editorial

Let f(P,c)f(P,c)f(P,c) be the number of traversals in walk PPP whose color is not ccc. Its cost is min⁡cf(P,c)\min_c f(P,c)minc​f(P,c), so the answer is min⁡Pmin⁡cf(P,c)=min⁡cmin⁡Pf(P,c)\min_P\min_c f(P,c)=\min_c\min_P f(P,c)minP​minc​f(P,c)=. Fix a color ccc, assign weight 0 to its edges and 1 to other edges, and compute the shortest distance using 0-1 BFS. Minimize over all colors. Push zero-weight relaxations to the front of a deque and unit-weight relaxations to the back. Store the distance at insertion and discard stale entries. Time is O(K(V+E))O(K(V+E))O(K(V+E)) and space O(V+E)O(V+E)O(V+E). Nonnegative weights mean removing a cycle cannot increase the chosen-color cost. Thus subtask 1 may enumerate all simple paths by DFS and count colors; a loose bound is O(E!K)O(E!K)O(E!K), sufficient for E≤8E\leq8E≤8. The answer is between 0 and V−1V-1V−1, as are finite shortest distances, so all arithmetic fits signed 64-bit integers.

Solution written by GPT6.1

minc​
minP​
f
(
P
,
c
)