問題

You are given a $10^9 \times 10^9$ matrix $A$. Initially, all entries equal to $0$.
First, process following $N$ operations.

  • l d r u w: Add $w$ to all entries $A_{xy}$ satisfying $l\leq x < r$ and $d \leq y < u$.

Then, process following $Q$ queries.

  • l d r u: Calculate the sum of entries $A_{xy}$ satisfying $l\leq x < r$ and $d \leq y < u$, and print it modulo $998244353$.

做法

首先考慮差分陣列 $D[i][j]$,有:

$$A[i][j] = \sum_{x=0}^i \sum_{y=0}^j D[x][y]$$


而將整個矩形 $[l, d] \times [r, u]$ 加上 $w$,可以改成:

  • $D[l][d] += w$
  • $D[l][u + 1] -= w$
  • $D[r + 1][d] -= w$
  • $D[r + 1][u + 1] += w$

對於每次詢問範圍 $[l, d] \times [r, u]$ ,可以由四個「從 $(0,0)$ 出發的左下角前綴矩形」加減得到:

$$ Q(l, d, r, u) = S(r, u) - S(l-1, u) - S(r, d-1) + S(l-1, d-1) \\ S(X, Y) = \sum_{i=0}^X \sum_{j=0}^Y A[i][j] $$

現在的問題是如何快速計算 $S(x,y)$,展開 $S(x,y)$ 成差分矩陣:

$$ \begin{align*} S(X, Y) &= \sum_{i=0}^X \sum_{j=0}^Y A[i][j] \\ &= \sum_{i=0}^X \sum_{j=0}^Y \sum_{x=0}^i \sum_{y=0}^j D[x][y] \end{align*} $$

每個 $D[x][y]$ 都會被算進 $A[i][j]$ 中,其中 $x, y$ 滿足 $0 \le x \le i$ 與 $0 \le y \le j$。換句話說,每個 $i, j$ 滿足 $i \ge x$ 與 $j \ge y$ 都會算過一遍 $D[x][y]$。

因此可以把 $S(X,Y)$ 改寫成:

$$ \begin{align*} S(X, Y) &= \sum_{i=0}^X \sum_{j=0}^Y \sum_{x=0}^i \sum_{y=0}^j D[x][y] \\ &= \sum_{x=0}^{X} \sum_{y=0}^{Y} \left( \sum_{i=x}^{X} \sum_{j=y}^{Y} D[x][y] \right) \\ &= \sum_{x=0}^{X} \sum_{y=0}^{Y} D[x][y] \times \left( \sum_{i=x}^{X} 1 \right) \times \left( \sum_{j=y}^{Y} 1 \right) \\ &= \sum_{x=0}^X \sum_{y=0}^Y D[x][y] \times (X - x + 1) \times (Y - y + 1) \end{align*} $$


展開這個後半部份 $(X-x+1) \times (Y-y+1)$:

$$ \begin{align*} S(X, Y) &= \sum_{x=0}^X \sum_{y=0}^Y D[x][y] \times (X - x + 1) \times (Y - y + 1) \\ &= \sum_{x=0}^{X} \sum_{y=0}^{Y} D[x][y] \Big[ (X+1)(Y+1) - (Y+1)x - (X+1)y + xy \Big] \end{align*} $$

於是就有:

$$ \begin{align*} S(X, Y) = &(X+1)(Y+1)\underbrace{\sum D[x][y]}_{\text{BIT}_1} \\ &- (Y+1)\underbrace{\sum x \cdot D[x][y]}_{\text{BIT}_2} \\ &- (X+1)\underbrace{\sum y \cdot D[x][y]}_{\text{BIT}_3} \\ &+ \underbrace{\sum xy \cdot D[x][y]}_{\text{BIT}_4} \end{align*} $$

每個點 $(x, y)$ 只要在對應的四棵樹狀數組中分別維護以下四種權重:

  1. $\text{BIT}_1$:維護 $D[x][y]$
  2. $\text{BIT}_2$:維護 $x \cdot D[x][y]$
  3. $\text{BIT}_3$:維護 $y \cdot D[x][y]$
  4. $\text{BIT}_4$:維護 $x \cdot y \cdot D[x][y]$

每個詢問 $Q(l,d,r,u)$ 都可以拆成詢問四個 $S(X,Y)$ ,而每次修改都可以拆成四個 BIT 分別修改,接下來只要離散化 $y$ 座標,然後將這些詢問與修改依照 $x$ 座標排序並依序處理,便可快速計算每個詢問。

每個詢問會花 $4 \times 4 \times Q \times \log N$,每次修改會花 $4 \times \log N$,總時間複雜度為 $O(N \log N + Q \log N)$。