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

Fast Calculate

Back to problem

Editorial

If N=1N=1N=1, the inner sum is empty, so the answer is 000. Assume N≥2N\geq 2N≥2 below.

For a fixed ddd, define

Hd=∑1≤i<j≤N(d−1)i−1dj−i−1(d+1)N−j.H_d=\sum_{1\leq i<j\leq N}(d-1)^{i-1}d^{j-i-1}(d+1)^{N-j}.Hd​=1≤i<j≤N

Let x=i−1x=i-1x=i−1, y=j−i−1y=j-i-1y=j−i−1, and z=N−jz=N-jz. Then are nonnegative integers satisfying , hence

Hd=∑x+y+z=N−2(d−1)xdy(d+1)z.H_d=\sum_{x+y+z=N-2}(d-1)^x d^y(d+1)^z.Hd​=x+y+z=N−2

For three distinct values a,b,ca,b,ca,b,c,

∑x+y+z=kaxbycz=ak+2(a−b)(a−c)+bk+2(b−a)(b−c)+ck+2(c−a)(c−b).\sum_{x+y+z=k}a^x b^y c^z = \frac{a^{k+2}}{(a-b)(a-c)} + \frac{b^{k+2}}{(b-a)(b-c)} + \frac{c^{k+2}}{(c-a)(c-b)}.x+y+z=k

Substituting a=d−1a=d-1a=d−1, b=db=db=d, c=d+1c=d+1c=d+1, and gives

Hd=(d−1)N−2dN+(d+1)N2.H_d=\frac{(d-1)^N-2d^N+(d+1)^N}{2}.Hd​=2(d−1)

Let fd=dNf_d=d^Nfd​=dN. Twice the required value is

∑d=1M−1(M−d)(fd−1−2fd+fd+1).\sum_{d=1}^{M-1}(M-d)(f_{d-1}-2f_d+f_{d+1}).d=1∑M−1​(M−d)(f

After collecting the coefficient of each fkf_kfk​, every coefficient for 2≤k≤M−12\leq k\leq M-12≤k≤M−1 cancels, and only fM−Mf1f_M-Mf_1 remains. Since , the original expression equals

MN−M2.\frac{M^N-M}{2}.2MN−M​.

Compute MNM^NMN by binary exponentiation and multiply by the modular inverse of 222, which is 499 122 177499\,122\,177499122177 modulo 998 244 353998\,244\,353998244353.

The time complexity is O(log⁡N)O(\log N)O(logN) and the memory complexity is O(1)O(1)O(1).

Solution written by GPT5.6

∑
​
(
d
−
1)i−1dj−i−1(d+
1)N−j.
=
N−
j
x,y,zx,y,zx,y,z
x+y+z=N−2x+y+z=N-2x+y+z=N−2
∑
​
(
d
−
1)xdy(d+
1)z.
∑
​
ax
by
cz
=
(a−b)(a−c)ak+2​+
(b−a)(b−c)bk+2​+
(c−a)(c−b)ck+2​.
k=N−2k=N-2
k=N−2
N
−
2
dN
+
(
d
+
1
)N
​
.
d−1​
−
2fd​+
fd+1​).
fM​−Mf1​
f1=1f_1=1f1​=1