---
id: 1915
lang: en
translation_of: index.md
source_sha256: 8e786b46702f87c26b616c2c49037e4e8afbeaba0453545120bf58d21b5e13e5
title: "Fast Walsh Transform | FWT"
description: "FWT's Or, And and Xor transform formulas with template code, plus two applications: CF662C Binary Table and LOJ 152 Subset Convolution."
tags: ["OI","Math","FWT"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Title separator ｜ (full-width bar) rendered as |."
  - "全剧最优解 (sic) read as 全局最优解, “global optimum”."
  - "压起来 (literally “press together”) rendered as “compress”."
---

## Quick Start

Memorize the formulas:

```text
Or operation:

    arr[k + step] += opt * arr[k]

And operation:

    arr[k] += opt * arr[k + step]

Xor operation:

    A = arr[k], B = arr[k + step]

    arr[k] = A + B, arr[k + step] = A - B

    with inverse-operation, the inv2 is needed:

    arr[k] /= 2, arr[k + step] /= 2;
```

<!--more-->

```cpp
// P4717.cpp
// NTT;
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = (1 << 17) + 200, mod = 998244353;

int n, Ai[MAX_N], Bi[MAX_N], C[MAX_N], A[MAX_N], B[MAX_N];

int quick_pow(int bas, int tim)
{
    int ret = 1;
    while (tim)
    {
        if (tim & 1)
            ret = 1LL * ret * bas % mod;
        bas = 1LL * bas * bas % mod;
        tim >>= 1;
    }
    return ret;
}

const int inv2 = quick_pow(2, mod - 2);

void fwt_or(int *arr, int opt)
{
    for (int step = 1; step < n; step <<= 1)
        for (int j = 0; j < n; j += (step << 1))
            for (int k = j; k < j + step; k++)
                arr[k + step] = (1LL * arr[k + step] + mod + 1LL * arr[k] * opt) % mod;
}

void fwt_and(int *arr, int opt)
{
    for (int step = 1; step < n; step <<= 1)
        for (int j = 0; j < n; j += (step << 1))
            for (int k = j; k < j + step; k++)
                arr[k] = (1LL * arr[k] + mod + 1LL * arr[k + step] * opt) % mod;
}

void fwt_xor(int *arr, int opt)
{
    for (int step = 1; step < n; step <<= 1)
        for (int j = 0; j < n; j += (step << 1))
            for (int k = j; k < j + step; k++)
            {
                int A = arr[k], B = arr[k + step];
                arr[k] = (1LL * A + B) % mod, arr[k + step] = (1LL * A + mod - B) % mod;
                if (opt == -1)
                    arr[k] = 1LL * arr[k] * inv2 % mod, arr[k + step] = 1LL * arr[k + step] * inv2 % mod;
            }
}

int main()
{
    scanf("%d", &n), n = 1 << n;
    for (int i = 0; i < n; i++)
        scanf("%d", &Ai[i]);
    for (int i = 0; i < n; i++)
        scanf("%d", &Bi[i]);

    memcpy(A, Ai, sizeof(A)), memcpy(B, Bi, sizeof(B));
    fwt_or(A, 1), fwt_or(B, 1);
    for (int i = 0; i < n; i++)
        C[i] = 1LL * A[i] * B[i] % mod;
    fwt_or(C, -1);
    for (int i = 0; i < n; i++)
        printf("%d ", C[i]);
    puts("");

    memcpy(A, Ai, sizeof(A)), memcpy(B, Bi, sizeof(B));
    fwt_and(A, 1), fwt_and(B, 1);
    for (int i = 0; i < n; i++)
        C[i] = 1LL * A[i] * B[i] % mod;
    fwt_and(C, -1);
    for (int i = 0; i < n; i++)
        printf("%d ", C[i]);
    puts("");

    memcpy(A, Ai, sizeof(A)), memcpy(B, Bi, sizeof(B));
    fwt_xor(A, 1), fwt_xor(B, 1);
    for (int i = 0; i < n; i++)
        C[i] = 1LL * A[i] * B[i] % mod;
    fwt_xor(C, -1);
    for (int i = 0; i < n; i++)
        printf("%d ", C[i]);
    puts("");
    return 0;
}
```

## Applications

**CF662C Binary Table**

Notice that $n$ is very small, so we can consider compressing each column, then counting how many identical columns there are. If we enumerate the row-flip state $S$ (a $1$ in the first bit means the first row is flipped), apply the operations, and then do one sweep, handling each column case by case, we get a local optimum, which we then combine into the global optimum. This has a very high time complexity, but we can see potential room for optimization. We can try to sum it up mathematically:

$$
\sum_{S = 0}^{2^n - 1} \sum_{x \text{xor} y = S} cnt[x] \cdot best[y]
$$

Here, we turn a column that was originally $x$ into $y$, and the contribution of $y$ is naturally $\min\{ \text{number of 0s}, \text{number of 1s} \}$.

```cpp
// CF662C.cpp
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAX_N = 22, MAX_M = 1e5 + 200;

int n, m;
ll ai[1 << MAX_N], bi[1 << MAX_N], stats[MAX_M], poly_siz;

void fwt_xor(ll *arr, int opt)
{
    for (int step = 1; step < poly_siz; step <<= 1)
        for (int j = 0; j < poly_siz; j += (step << 1))
            for (int k = j; k < j + step; k++)
            {
                ll A = arr[k], B = arr[k + step];
                arr[k] = A + B, arr[k + step] = A - B;
                if (opt == -1)
                    arr[k] >>= 1, arr[k + step] >>= 1;
            }
}

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
        for (int j = 1, val; j <= m; j++)
            scanf("%1d", &val), stats[j] |= (val << (i - 1));
    for (int i = 1; i <= m; i++)
        ai[stats[i]]++;
    for (int i = 0; i < (1 << n); i++)
        bi[i] = min(__builtin_popcount(i), n - __builtin_popcount(i));
    poly_siz = 1LL << n;
    fwt_xor(ai, 1), fwt_xor(bi, 1);
    for (int i = 0; i < poly_siz; i++)
        ai[i] *= bi[i];
    fwt_xor(ai, -1);
    ll ans = 0x3f3f3f3f3f3f3f3f;
    for (int i = 0; i < poly_siz; i++)
        ans = min(ans, ai[i]);
    printf("%lld\n", ans);
    return 0;
}
```

---

**LOJ 152 Subset Convolution**

Subset convolution is:

$$
\sum_{S \subset U} f_S g_{U - S}
$$

Now the problem asks us to solve it for each different $U$. We can consider classifying $f$ and $g$ by the number of bits that are $1$, turning them into $\{f_b\}$ and $\{g_b\}$, and then doing FWT_OR on the $n$ polynomials by bit count, which gives us their subset expansions. We only need to enumerate the size of the full set $|U|$ and the size of one subset $|S|$, then multiply the expanded ones together and store the result in the answer for $|U|$. When outputting the answer, take care to extract it from the polynomial with the corresponding count.

```cpp
#pragma GCC optimize(2)
// LOJ152.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = (1 << 22) + 2000, mod = 1e9 + 9;

int n, fi[22][MAX_N], gi[22][MAX_N], poly_siz, cnt[MAX_N], ans[22][MAX_N], gans[MAX_N];

inline char nc()
{
    static char buf[10000000], *p1 = buf, *p2 = buf;
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 10000000, stdin), p1 == p2) ? EOF : *p1++;
}

int read()
{
    int x = 0, f = 1;
    char ch = nc();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = nc();
    }
    while (isdigit(ch))
        x = (x << 3) + (x << 1) + ch - '0', ch = nc();
    return x * f;
}

inline void fwt_or(int *arr, int opt)
{
    for (int step = 1; step < poly_siz; step <<= 1)
        for (int j = 0; j < poly_siz; j += (step << 1))
            for (int k = j; k < j + step; k++)
                arr[k + step] = (1LL * arr[k + step] + mod + 1LL * opt * arr[k]) % mod;
}

int main()
{
    n = read(), poly_siz = (1 << n);
    for (int i = 0; i <= poly_siz; i++)
        cnt[i] = cnt[i >> 1] + (i & 1);
    for (int i = 0; i < poly_siz; i++)
        fi[cnt[i]][i] += read();
    for (int i = 0; i < poly_siz; i++)
        gi[cnt[i]][i] += read();
    for (int i = 0; i <= n; i++)
        fwt_or(fi[i], 1), fwt_or(gi[i], 1);
    for (int i = 0; i <= n; i++)
        for (int j = 0; j <= i; j++)
            for (int k = 0; k < poly_siz; k++)
                ans[i][k] = (1LL * ans[i][k] + 1LL * fi[i - j][k] * gi[j][k] % mod) % mod;
    for (int i = 0; i <= n; i++)
        fwt_or(ans[i], -1);
    for (int i = 0; i < poly_siz; i++)
        printf("%d ", ans[cnt[i]][i]);
    puts("");
    return 0;
}
```
