DOJ logoDOJ
Problems
Recently added problemsSaved problems
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

Reading KakaoTalk

Back to problem

Editorial

For each person ppp, define

Lp=max⁡({i∣Ai=p}∪{0}),L_p=\max(\{i\mid A_i=p\}\cup\{0\}),Lp​=max({i∣Ai​=p}∪{0}),

the index of the last message written by that person. The author condition is equivalent to Cp≥LpC_p\ge L_pCp​≥Lp​.

Set B0=NB_0=NB0​=N and BM+1=0B_{M+1}=0BM+1​=0. Let be the number of people whose last read message is exactly . Then

Dk=Bk−Bk+1(0≤k≤M).D_k=B_k-B_{k+1}\qquad(0\le k\le M).Dk​=Bk​−B

The input guarantees that BBB is non-increasing, so every DkD_kDk​ is a nonnegative integer.

Let EkE_kEk​ be the number of people satisfying Lp≤kL_p\le kLp​≤k. Only these people may have Cp=kC_p=k.

Choose the people with Cp=kC_p=kCp​=k in increasing order of kkk. Before processing kkk, exactly

N−BkN-B_kN−Bk​

people have already received values smaller than kkk. Every such person satisfies Lp≤kL_p\le kLp​≤k. Therefore, the number of unassigned people who may receive value kkk is

Ek−(N−Bk).E_k-(N-B_k).Ek​−(N−Bk​).

We must choose exactly DkD_kDk​ of them. Hence the answer is

∏k=0M(Ek−(N−Bk)Dk).\prod_{k=0}^{M}\binom{E_k-(N-B_k)}{D_k}.k=0∏M​(D

The problem guarantees that at least one valid sequence exists, so every selection step is feasible. An implementation may still check whether an upper argument is negative or smaller than DkD_kDk​.

Compute every LpL_pLp​, count their frequencies, and take prefix sums to obtain all EkE_kEk​. With factorials and inverse factorials, each binomial coefficient is evaluated in constant time.

The time complexity is O(N+M)O(N+M)O(N+M) and the memory complexity is O(N+M)O(N+M)O(N+M).

DkD_kDk​
kkk
k+1
​
(
0
≤
k≤
M).
Cp​
=
k
k
​
Ek​−(N−Bk​)
​
)
.