PS: Fast Walsh–Hadamard Transform

[BOJ 13758] RNG 2

Task

For given integers $1\le N\le20000$ and $1\le K\le50000$, compute:

\[ \card{\Set{(x_1,\ldots,x_N)\in[0:K]^N\mid x_1\oplus\cdots\oplus x_N\ne0}} \pmod{30011} \]

Solution

Put $b=\lceil\log_2(K+1)\rceil$, $B=2^b$, $V_b=[0:B-1]$, and $P=30011$. Define:

\[ a(x)= \begin{cases} 1 &; 0\le x\le K \nl 0 &; K<x<B \end{cases} \]

Let $c_n(z)$ count length-$n$ arrays whose XOR is $z$. Appending one element gives an XOR convolution:

\[ c_{n+1}(z)=\sum_{x\oplus y=z}c_n(x)a(y), \qquad c_1=a \]

Thus $c_N=a^{\ast_\oplus N}$, the $N$-fold XOR convolution of $a$. Write $\mathcal{H}_b$ for the unnormalized Walsh transform and $\widehat a=\mathcal{H}_ba$. Convolution becomes pointwise multiplication, so:

\[ (\mathcal{H}_bc_N)(s)=\widehat a(s)^N \]

Only $c_N(0)$ is needed. The zero-coordinate row of the inverse transform is constant, giving:

\[ c_N(0)=B^{-1}\sum_{s\in V_b}\widehat a(s)^N \pmod P \]

The inverse $B^{-1}$ exists because $B$ is a power of two and $P$ is odd. Subtracting the zero-XOR arrays from all arrays gives:

\[ \boxed{(K+1)^N-B^{-1}\sum_{s\in V_b}\widehat a(s)^N} \pmod P \]

Compute $\widehat a$ by one FWHT and each power by binary exponentiation. A complete inverse transform is unnecessary. All transform and exponentiation arithmetic is modulo $P$.

Complexity

The FWHT takes $O(B\log B)$ time and the $B$ exponentiations take $O(B\log N)$ time. Thus:

\[ O\left(B(\log B+\log N)\right)\text{ time}, \qquad O(B)\text{ memory} \]

[BOJ 14878] 부분 수열 XOR합

Task

An array $a_0,\ldots,a_{N-1}$ is given, where $N\le10^5$ and $1\le a_i<2^{16}$. For $k\in[0:2^{16}-1]$, let:

\[ C(k)=\card{\Set{(l,r)\mid 0\le l<r\le N,\quad \bigoplus_{i=l}^{r-1}a_i=k}} \]

Find $k_\ast=\min\argmax_k C(k)$ and output $(k_\ast,C(k_\ast))$.

Solution

Put $b=16$, $V_b=[0:2^b-1]$, and define the prefix XORs and their frequency function by:

\[ p_0=0,\qquad p_{i+1}=p_i\oplus a_i,\qquad f(x)=\card{\Set{i\in[0:N]\mid p_i=x}} \]

Since $\bigoplus_{i=l}^{r-1}a_i=p_l\oplus p_r$, consider:

\[ \begin{align*} R(k)&=(f\ast_\oplus f)(k) \nl &=\sum_{x\in V_b}f(x)f(x\oplus k) \nl &=\card{\Set{(l,r)\in[0:N]^2\mid p_l\oplus p_r=k}}. \end{align*} \]

This counts ordered pairs of prefix positions. The $N+1$ diagonal pairs contribute only to $R(0)$. Every remaining pair occurs in both orders, and exactly one order has $l<r$. Thus:

\[ C(k)= \begin{cases} \dfrac{R(0)-(N+1)}2 &; k=0 \nl \dfrac{R(k)}2 &; k\ne0 \end{cases} \]

Compute all $R(k)$ by:

\[ R=\mathcal{H}_b^{-1}\left((\mathcal{H}_bf)^2\right) \]

Then scan $k$ in increasing order, replacing the answer only when the frequency strictly increases. As a check:

\[ \sum_{k\in V_b}C(k)=\binom{N+1}{2} \]

All calculations can be done with signed 64-bit integers. Indeed, $\abs{(\mathcal{H}_bf)(s)}\le N+1$, and every intermediate value in the unnormalized inverse is bounded by $2^b(N+1)^2<2^{63}$.

Complexity

Computing the prefix frequencies takes $O(N)$ time. The two transforms and final scan take $O(b2^b)$ time, so the total is:

\[ O(N+b2^b)\text{ time},\qquad O(2^b)\text{ memory} \]

The prefix XORs can be processed without storing the array.

[BOJ 21066] Game on a Tree

Task

There are $M$ players, $C\le20$ colors, and a tree $T=(V,E)$ with $N$ vertices. Color $c$ has an integer value $p_c\in[0:10^9]$. A deck is a mask $d\in V_C=(\mathbb{F}_2)^C$, with score:

\[ g(d)= \begin{cases} 0 &; d=0 \nl \gcd\Set{p_c\mid d_c=1} &; d\ne0 \end{cases} \]

Each vertex $v$ has a color $c_v$. In round $r$, two distinct vertices $u_r,v_r$ are chosen. Every player toggles every color encountered on the path between them, including both endpoints. The player for that round receives the sum of all deck scores. Then one vertex is recolored.

Given the initial decks and all rounds, compute the $M$ scores modulo $P=10^9+7$. Here $N,M\le10^5$.

Solution

Let $d_j$ be player $j$’s initial deck and define:

\[ f(x)=\card{\Set{j\in[0:M-1]\mid d_j=x}} \]

For a round, the common change to every deck is:

\[ q_r=\bigoplus_{v\in P_T(u_r,v_r)}2^{c_v} \]

where $P_T(u,v)$ is the vertex set of the unique path. Thus, after the path operation in round $r$:

\[ \tau_0=0,\qquad \tau_r=\tau_{r-1}\oplus q_r,\qquad d_j^{(r)}=d_j\oplus\tau_r \]

The total score depends only on $\tau_r$. For every $\tau\in V_C$, put:

\[ \begin{align*} A(\tau)&=\sum_{j=0}^{M-1}g(d_j\oplus\tau) \nl &=\sum_{x\in V_C}f(x)g(x\oplus\tau) \nl &=(f\ast_\oplus g)(\tau). \end{align*} \]

Therefore all possible total scores can be precomputed at once:

\[ A=\mathcal{H}_C^{-1} \left((\mathcal{H}_Cf)\cdot(\mathcal{H}_Cg)\right) \pmod P \]

To compute $g$, choose any set bit $c$ of a nonzero mask $d$:

\[ g(d)=\gcd\left(g(d\oplus2^c),p_c\right),\qquad g(0)=0 \]

The gcds are computed over the integers; their residues are used in the transform.


It remains to maintain the path XORs under vertex recoloring. Root the tree at $o$ and write:

\[ R(v)=\bigoplus_{w\in P_T(o,v)}2^{c_w} \]

For $a=\operatorname{LCA}(u,v)$, the common root path cancels twice, giving:

\[ q(u,v)=R(u)\oplus R(v)\oplus2^{c_a} \]

Suppose vertex $w$ changes from color $c$ to color $c^\prime$. Put $\Delta=2^c\oplus2^{c^\prime}$. Then $R(v)$ changes by XOR with $\Delta$ exactly when $v$ belongs to the subtree of $w$.

An Euler tour maps this subtree to $[\operatorname{tin}(w):\operatorname{tout}(w)]$. Let $R_0(v)$ be the initial root-path XOR. Maintain the changes in a Fenwick tree over XOR differences:

\[ \begin{align*} D(\operatorname{tin}(w))&\gets D(\operatorname{tin}(w))\oplus\Delta, \nl D(\operatorname{tout}(w)+1)&\gets D(\operatorname{tout}(w)+1)\oplus\Delta, \nl R(v)&=R_0(v)\oplus \bigoplus_{t\le\operatorname{tin}(v)}D(t). \end{align*} \]

The second update is omitted if its index exceeds $N$. Precompute binary-lifting ancestors for LCA queries. For each round, compute $q_r$, update $\tau_r$, and return $A(\tau_r)$. Apply the vertex recoloring afterward, so that it affects subsequent rounds.

Complexity

Let $L$ be the total number of cards in the initial decks and $W=\max(2,p_0,\ldots,p_{C-1})$. Building $f$ takes $O(L+M)$ time. The gcd recurrence takes $O(2^C\log W)$ time, and the transforms take $O(C2^C)$ time.

LCA preprocessing takes $O(N\log N)$ time. Each round uses $O(\log N)$ time for the path query and recoloring. Thus:

\[ O\left(L+(N+M)\log N+2^C(C+\log W)\right)\text{ time}, \qquad O(2^C+N\log N)\text{ memory} \]

[BOJ 18536] Tritwise Mex

Task

Put $\mu(a,b)=\min(\mathbb{N}_0\setminus\{a,b\})$. For $x,y\in[0:3^k-1]$ with ternary digits $x_t,y_t$, define:

\[ \mu_k(x,y)=\sum_{t=0}^{k-1}\mu(x_t,y_t)3^t \]

Two arrays $A,B\in[0:10^3]^{3^k}$ are given, where $1\le k\le12$. Compute:

\[ C_z=\sum_{\mu_k(x,y)=z}A_xB_y \qquad(0\le z<3^k) \]

Solution

This is a related digitwise convolution. The mex operation is not associative, so the XOR convolution theorem does not apply directly. Instead, factor its one-digit bilinear map.

The one-digit operation table is:

\[ \left(\mu(a,b)\right)_{a,b=0}^2= \begin{pmatrix} 1&2&1 \nl 2&0&0 \nl 1&0&0 \end{pmatrix} \]

Let $\star_k$ denote convolution under $\mu_k$. Split the arrays according to the highest ternary digit:

\[ A_i=(A_{i3^{k-1}+t})_{0\le t<3^{k-1}}, \qquad B_i=(B_{i3^{k-1}+t})_{0\le t<3^{k-1}} \qquad(i=0,1,2) \]

Write $\star=\star_{k-1}$. The three output blocks satisfy:

\[ \begin{align*} C_0&=A_1\star B_1+A_1\star B_2+A_2\star B_1+A_2\star B_2, \nl C_1&=A_0\star B_0+A_0\star B_2+A_2\star B_0, \nl C_2&=A_0\star B_1+A_1\star B_0. \end{align*} \]

Direct recursion would make nine recursive calls. By bilinearity, only four are needed:

\[ \begin{align*} U&=(A_1+A_2)\star(B_1+B_2), \nl V&=(A_0+A_1+A_2)\star(B_0+B_1+B_2), \nl W&=A_0\star B_1,\qquad Z=A_1\star B_0. \end{align*} \]

Then:

\[ C_0=U,\qquad C_1=V-U-W-Z,\qquad C_2=W+Z \]

Indeed, $V$ contains all nine block products, while $U$ and $W+Z$ contain exactly the products for outputs $0$ and $2$. The recursion ends at $k=0$, where $\star_0$ is scalar multiplication.

Thus we replace the Hadamard factorization for one XOR bit by a four-product factorization for one mex digit, and apply it recursively to all digits.

Complexity

The running time satisfies:

\[ T(k)=4T(k-1)+O(3^k)=O(4^k) \]

Evaluating the four recursive calls sequentially and releasing temporary arrays gives:

\[ S(k)=S(k-1)+O(3^k)=O(3^k) \]

memory. In particular, the method avoids enumerating all $9^k$ pairs of indices. Signed 64-bit integers suffice since every recursive input sum is at most $10^3\cdot3^k$, and every output or partial sum is bounded by:

\[ \left(\sum_xA_x\right)\left(\sum_yB_y\right) \le10^6\cdot9^{12}<2^{63} \]

[BOJ 34176] 이 대회에 원이 등장할 수 없는 이유는?

Task

Let $V=(\mathbb{F}_2)^N$, where $N\le20$, and let $f:V\to\mathbb{F}_2$ be given by its truth table. For a coordinate permutation $\sigma$, write $P_\sigma$ for its permutation matrix, with:

\[ (P_\sigma x)_i=x_{\sigma(i)},\qquad g_{\sigma,v}(x)=P_\sigma x+v \]

All vector and matrix operations in this section are over $\mathbb{F}_2$. The affine symmetries form a group:

\[ G_f=\Set{(P_\sigma,v)\mid f(P_\sigma x+v)=f(x)\text{ for all }x\in V} \]

There is a generating list $(P_{\sigma^1},v_1),\ldots,(P_{\sigma^M},v_M)$ of $G_f$, where $M\le20$. Only the permutations $\sigma^i$ remain known. For each of $Q\le1000$ queries $(k,\pi)$, compute:

\[ \card{\Set{v\in V\mid f\circ g_{\pi,v}^{\,k}=f}} \pmod{998244353}, \qquad 0\le k\le10^{18} \]

Solution

First, project the symmetry group onto its permutation part:

\[ B=\Set{A\mid \exists u,\ (A,u)\in G_f} =\langle P_{\sigma^1},\ldots,P_{\sigma^M}\rangle \]

The equality follows because projection is a group homomorphism and the given affine maps generate all of $G_f$. Build a Schreier–Sims stabilizer chain for $B$. This permits membership tests without enumerating the group.

For a query, put $\Pi=P_\pi$. Repeated composition gives:

\[ g_{\pi,v}^{\,k}(x)=Ax+Lv,\qquad A=\Pi^k,\qquad L=\sum_{j=0}^{k-1}\Pi^j \]

For $k=0$, use $A=I$ and $L=0$. If $A\notin B$, the answer is zero. We may therefore assume that $A\in B$, so at least one shift $u$ satisfies $(A,u)\in G_f$.


Put $F(x)=(-1)^{f(x)}$ and compute its integer Walsh transform $\widehat F=\mathcal{H}_NF$. A change of variables in the transform gives:

\[ F(Ax+u)=F(x)\text{ for all }x \iff \widehat F(A^{\mathsf T}s)=(-1)^{\langle s,u\rangle}\widehat F(s) \text{ for all }s \]

Let:

\[ \mathcal{S}=\Set{s\in V\mid\widehat F(s)\ne0},\qquad W=\operatorname{span}_{\mathbb{F}_2}\mathcal{S} \]

In particular, the translation symmetries are exactly:

\[ K=\Set{u\in V\mid F(x+u)=F(x)\text{ for all }x} =W^\perp \]

Choose a basis $s_1,\ldots,s_r$ of $W$ consisting of masks from $\mathcal{S}$. Retain these original support masks when selecting the basis. For $A\in B$, existence of a valid shift guarantees:

\[ \widehat F(A^{\mathsf T}s_i) =(-1)^{\beta_i(A)}\widehat F(s_i), \qquad \beta_i(A)\in\mathbb{F}_2 \]

Thus $\beta_i(A)$ is determined by whether the two nonzero coefficients have the same or opposite signs. Moreover:

\[ (A,u)\in G_f \iff \langle s_i,u\rangle=\beta_i(A) \quad(1\le i\le r) \]

Proof. Fix one valid shift $u_0$ for $A$. The basis equations hold for $u$ precisely when $u+u_0\in W^\perp=K$. Translation by $u+u_0$ preserves $F$, so:

\[ F(Ax+u)=F(Ax+u_0)=F(x) \]

The converse follows from the Fourier identity above.


Substitute $u=Lv$. The query becomes a linear system with at most $N$ equations:

\[ \langle L^{\mathsf T}s_i,v\rangle=\beta_i(A) \qquad(1\le i\le r) \]

Let $D$ have rows $(L^{\mathsf T}s_i)^{\mathsf T}$, and let $\beta=(\beta_i(A))_{i=1}^r$. Gaussian elimination over $\mathbb{F}_2$ gives:

\[ \text{answer}= \begin{cases} 0 &; \operatorname{rank}[D\mid\beta]>\operatorname{rank}D \nl 2^{N-\operatorname{rank}D} &; \text{otherwise} \end{cases} \pmod{998244353} \]

Only the selected Fourier coefficients are needed for each query. The other coefficients need not be inspected again.

We can also compute $A$ and $L$ without iterating $k$ times. On a cycle of $\pi$ of length $d$, write $k=qd+t$, where $0\le t<d$. If $\Pi_d$ is the permutation matrix restricted to this cycle and $J_d$ is the all-ones matrix, then:

\[ A\big|_d=\Pi_d^t,\qquad L\big|_d=(q\bmod2)J_d+\sum_{j=0}^{t-1}\Pi_d^j \]

Indeed, every complete cycle contributes $\sum_{j=0}^{d-1}\Pi_d^j=J_d$, and two identical contributions cancel over $\mathbb{F}_2$. For $k=0$, $D=0$ and $\beta=0$, giving $2^N$ as required.

Complexity

The integer FWHT and support-basis selection take $O(N2^N)$ time. Using Knuth’s deterministic Schreier–Sims variant, group preprocessing takes $O(N^5+MN^2)$ time and $O(N^3)$ memory. A membership test takes $O(N^2)$ time.

Since $N\le20$, a binary row fits in one machine word. Cycle decomposition, construction of the query equations, and elimination take $O(N^2)$ word operations per query. Thus:

\[ O\left(N2^N+N^5+(M+Q)N^2\right)\text{ time}, \qquad O(2^N+N^3)\text{ memory} \]

The Fourier coefficients must be kept as exact integers so that their zeros and signs remain available.