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

Pepero Gifts

Back to problem

Editorial

Subtask 1 Use a bitmask for the remaining people. For each state, enumerate a sender aaa and every nearest remaining receiver bbb, then transition to the state with both removed. Store decisions to recover a sequence. Time is O(2NN2)O(2^N N^2)O(2NN2) and space is O(2N+N2)O(2^N+N^2)O(2N+N2).

Optimal value Let D1,…,DND_1,\ldots,D_ND1​,…,DN​ be clockwise gaps between consecutive people, including DN=L−XN+X1D_N=L-X_N+X_1D. Let and be the sums of odd and even gaps. The answer is .

Any sequence induces a perfect matching. Choose the traveled shortest arc for each pair and count how many arcs cover each gap. At every person, exactly one arc has an endpoint there, so the coverage counts of its two incident gaps have opposite parity. Thus either every odd gap or every even gap has odd coverage. Total distance is at least min⁡(A,B)\min(A,B)min(A,B).

Choose the lighter of the two alternating adjacent matchings. Its total gap length is at most L/2L/2L/2, so every chosen gap is itself a shortest arc. It remains to execute this matching while obeying the nearest-person rule.

Execution order Among remaining people, chosen and unchosen gaps alternate. Write their sums as A≤BA\le BA≤B. If no chosen pair were legal from either endpoint, every chosen gap would be longer than both neighboring unchosen gaps. Summing gives 2A>2B2A>2B2A>2B, a contradiction. Therefore some chosen pair is legal in at least one direction.

Removing a legal pair of length ddd changes the sums to A−dA-dA−d and B+dB+dB+d, because its gap and its two neighboring unchosen gaps merge. The inequality is preserved, so the process continues to the end. With two people remaining, they are necessarily each other's nearest person.

Maintain current circular neighbors using a doubly linked list. At every step scan remaining people and execute a fixed matched pair when its distance is no larger than the sender's distances to both current neighbors. A nearest point on a circle is one of these neighbors. This yields O(N2)O(N^2)O(N2) time and O(N)O(N)O(N) space.

Solution written by GPT6.1

N​
=
L−
XN​+
X1​
AAA
BBB
min⁡(A,B)\min(A,B)min(A,B)