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

Nostalgiabait

Back to problem

Editorial

First consider the case X≥0X \geq 0X≥0. If X<0X<0X<0, construct a matrix for ∣X∣|X|∣X∣ and then transpose it. Transposition swaps rows and columns, so it swaps M1M_1M1​ and M2M_2M2​ and changes the sign of their difference.

Every row contains NNN distinct positive integers, so its maximum is at least NNN. Hence M2≥NM_2 \geq NM2​≥N. Also, the maxima of the NNN rows are distinct, so their minimum is at most . Therefore

N≤M2≤N2−N+1.N \leq M_2 \leq N^2-N+1.N≤M2​≤N2−N+1.

The same argument gives

N≤M1≤N2−N+1.N \leq M_1 \leq N^2-N+1.N≤M1​≤N2−N+1.

Thus a necessary condition is

∣X∣≤(N2−N+1)−N=(N−1)2.|X| \leq (N^2-N+1)-N=(N-1)^2.∣X∣≤(N2−N+1)−N=(

Now suppose 0≤X≤(N−1)20 \leq X \leq (N-1)^20≤X≤(N−1)2, and let K=N2−N+1K=N^2-N+1K=N.

Set

H1,1=K−X.H_{1,1}=K-X.H1,1​=K−X.

For every 2≤i≤N2 \leq i \leq N2≤i≤N, set

Hi,i=K+i−1.H_{i,i}=K+i-1.Hi,i​=K+i−1.

Thus the largest N−1N-1N−1 values K+1,K+2,⋯ ,N2K+1,K+2,\cdots,N^2K+1,K+2,⋯,N are placed on the diagonal.

If X>0X>0X>0, also set

H2,1=K.H_{2,1}=K.H2,1​=K.

Fill every still-empty cell from top-left to bottom-right with the smallest positive integer that has not been used yet.

When X>0X>0X>0, we have K−X≥NK-X \geq NK−X≥N. Hence the other N−1N-1N−1 cells of the first row receive values smaller than K−, so the maximum of the first row is . For every later row, its diagonal entry is its maximum. Therefore

M2=K−X.M_2=K-X.M2​=K−X.

Column 111 contains KKK, while each other column contains one of K+1,K+2,⋯ ,N2K+1,K+2,\cdots,N^2K+1,K+2,⋯,N. Hence

M1=K.M_1=K.M1​=K.

Thus M1−M2=XM_1-M_2=XM1​−M2​=X.

When X=0X=0X=0, we have H1,1=KH_{1,1}=KH1,1​=K, and the minimum row maximum and the minimum column maximum are both KKK, so the construction is also valid.

Therefore a solution exists exactly when ∣X∣≤(N−1)2|X| \leq (N-1)^2∣X∣≤(N−1)2. Filling the matrix takes O(N2)O(N^2)O(N2 time per case, or over the entire input.

Solution written by GPT5.6

N2−N+1N^2-N+1
N2−N+1
N
−
1)2.
2
−
N+
1
2
XK-X
K−X
K−XK-XK−X
2
)
O(∑N2)O\left(\sum N^2\right)O(∑N2)