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-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

candypinkmagicholeflipflop

Back to problem

Editorial

Sort the coins by increasing XiX_iXi​, and let wiw_iwi​ be the weight of the iii-th coin in this order.

Two unflipped coins are always compatible as neighbors, whereas two flipped coins are never compatible. If exactly one of two neighboring coins is flipped, the condition holds precisely when the flipped coin has the larger XXX.

Let fif_ifi​ be the number of flipped coins among the first iii coins in sorted order. Every flipped coin in such a prefix needs two neighboring, unflipped coins with smaller XXX. Unless the prefix contains the entire circular arrangement, the induced paths must therefore contain at least one more unflipped coin than flipped coins. Consequently every feasible selection satisfies

fi≤⌊i−12⌋(1≤i<N),fN≤⌊N2⌋.f_i \le \left\lfloor \frac{i-1}{2} \right\rfloor \quad (1 \le i < N), \qquad f_N \le \left\lfloor \frac{N}{2} \right\rfloor.fi​≤⌊2i

These inequalities are also sufficient. List the unflipped coins as u1,u2,…,umu_1,u_2,\ldots,u_mu1​,u2​,…,um​ and the flipped coins as , each in increasing order of . If , arrange them as . If , arrange in a circle. The prefix inequalities ensure that every flipped coin has strictly larger than each adjacent unflipped coin.

It remains to maximize the sum of weights subject to these nested prefix-cardinality limits. Process the coins in increasing order of XXX, inserting each weight into a min-heap. Whenever the heap size exceeds the limit for the current prefix, remove the smallest weight. The retained set is a maximum-weight feasible choice under all processed prefix limits. The final heap sum is the answer.

Sorting and heap operations take O(Nlog⁡N)O(N\log N)O(NlogN) time and O(N)O(N)O(N) space.

Solution written by GPT6

−
1
​
⌋
(
1
≤
i<
N),fN​≤
⌊2N​⌋.
v1,v2,…,vkv_1,v_2,\ldots,v_k
v1​,v2​,…,vk​
XXX
m>km>km>k
u1,v1,u2,v2,…,uk,vk,uk+1,uk+2,…,umu_1,v_1,u_2,v_2,\ldots,u_k,v_k,u_{k+1},u_{k+2},\ldots,u_mu1​,v1​,u2​,v2​,…,uk​,vk​,uk+1​,uk+2​,…,um​
m=km=km=k
u1,v1,u2,v2,…,uk,vku_1,v_1,u_2,v_2,\ldots,u_k,v_ku1​,v1​,u2​,v2​,…,uk​,vk​
XXX