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

Choosing Column Prefixes

Back to problem

Editorial

Increasing PjP_jPj​ by one adds APj+1+BjA_{P_j+1}+B_jAPj​+1​+Bj​. Because AAA is non-increasing, an optimum never needs to take a lower value in a column without taking every value above it. Hence the answer is the sum of the KKK largest values among all N2N^2N2 pair sums Ai+BjA_i+B_jAi​+Bj​.

After sorting BBB, the number of pair sums at least an integer xxx can be counted in O(Nlog⁡N)O(N\log N)O(NlogN) using binary search for every AiA_iAi​. Find the largest for which this count is at least . Sum every pair strictly greater than , then add for the remaining pairs. The answer may exceed 64-bit range, so a 128-bit integer is required.

xxx
KKK
xxx
xxx