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

tsp

Back to problem

Editorial

Rotating a Hamiltonian cycle does not change it, so fix vertex 111 as the start.

Let D[S][v]D[S][v]D[S][v] be the minimum weight of a path that starts at vertex 111, visits every vertex of SSS exactly once, and ends at vvv. Initially, D[{1}][1]=0D[\{1\}][1]=0D[{1}][1]=0. If an edge from vvv to an unvisited vertex uuu exists, update D[S∪{u}][u]D[S\cup\{u\}][u]D[S∪{u}][u] with D[S][v]+WvuD[S][v]+W_{vu}D[S][v]+Wvu​.

After visiting all vertices, add the weight of the edge returning to vertex 111 and choose the minimum. If no such value exists, print −1-1−1. Store the predecessor of each improved state to reconstruct the optimal cycle. Edge weight 000 is valid, so test for a missing edge using −1-1−1. A cycle can cost up to 18⋅10918\cdot10^918⋅10, requiring 64-bit integers.

The time complexity is O(N22N)O(N^2 2^N)O(N22N) and the space complexity is O(N2N)O(N2^N)O(N2N). For subtask , one can also fix the starting vertex and check every permutation of the remaining vertices.

Solution written by GPT6

9
11
1