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

Bitonic Tour

Back to problem

Editorial

View a valid tour as two increasing paths from vertex 111 to vertex NNN. They share only their endpoints.

Let D[i][j]D[i][j]D[i][j] be the minimum total weight of two such paths after assigning vertices 111 through jjj, with endpoints iii and jjj (i<ji<ji<j). Initially, D[1][2]=W12D[1][2]=W_{12}D[1][2]=W12​. When adding jjj, if i<j−1i<j-1i<j−1, append jjj after j−1j-1j−1, giving D[i][j]=D[i][j−1]+Wj−1,jD[i][j]=D[i][j-1]+W_{j-1,j}D[i][j]=D[i][j−1]+Wj−1. For i=j−1i=j-1i=j−1, append jjj after the other path's endpoint k<j−1k<j-1k<j−1, giving D[j−1][j]=min⁡k<j−1(D[k][j−1]+Wk,j)D[j-1][j]=\min_{k<j-1}(D[k][j-1]+W_{k,j})D[j−1][j]=mink<j−1​(. Missing edges cannot be used.

After processing every vertex, connect endpoints iii and NNN. The minimum of D[i][N]+Wi,ND[i][N]+W_{i,N}D[i][N]+Wi,N​ is the answer. Store the previous endpoint chosen for each to trace the selected edges backward and reconstruct both paths. If no tour exists, print . Edge weight is valid, so use to identify a missing edge. A tour can cost up to , requiring 64-bit integers.

The time and space complexities are both O(N2)O(N^2)O(N2). For subtask 111, one may enumerate every assignment of intermediate vertices to the two paths.

Solution written by GPT6

,
j
​
D
[
k
]
[
j
−
1]+
Wk,j​)
kkk
D[j−1][j]D[j-1][j]D[j−1][j]
−1-1−1
000
−1-1−1
2 000⋅1092\,000\cdot10^92000⋅109