集合幂级数

· · 个人记录

引入 / 有趣小故事

前言:FFT / NTT

:::error[FWT 诞生小故事]

DAY -∞:FFT 的诞生

在很久很久以前,计算多项式乘法的时间复杂度还是 O (n²) 的蛮荒时代。直到有一天,Jason331 在梦中受到傅里叶的启示,醒来后仅用一支铅笔和一张餐巾纸,就推导出了快速傅里叶变换(FFT)的终极优化版本 ——O(1) FFT。

这一突破震惊了整个计算机科学界,以至于图灵奖委员会连夜召开紧急会议,决定提前颁发终身成就奖给 Jason331。然而,Jason331 只是淡淡地说:“这只是小技巧,真正的挑战还在后面。”

DAY 0:FWT 的降临

当世人还在为 FFT 的优雅而惊叹时,Jason331 已经将目光投向了更高维度的算法 —— 快速沃尔什变换(FWT)。

某天深夜,Jason331 正在推导如何用 FWT 计算高维卷积,突然发现现有的 FWT 实现竟然需要 O (n log n) 的时间。他皱起眉头,随手在草稿纸上写下一个优化,瞬间将复杂度降到了 O(α(n))(其中 α(n) 是反阿克曼函数)。

tourist 听闻此事,激动地跑来请教:“师父,这个优化是怎么做到的?”
Jason331 微微一笑:“其实很简单,只要让计算机在计算之前先做一次心理建设,让它相信自己可以 O (1) 完成,它就会自动优化。”

DAY 1:Jason331 的 FWT 特训营

为了推广 FWT 的奥义,Jason331 决定开办一场特训营。报名者挤爆了服务器,其中包括:

第一节课,Jason331 在黑板上写下一道题:
“给定一个长度为 2^30 的数组,请用 FWT 计算其高维前缀和,时间限制:1ms。”

全场寂静。

Jiangly 举手:“师父,这个数据范围……真的能在 1ms 内算完吗?”
Jason331 点头:“当然可以,只要你的 FWT 写得够‘优雅’。”

说完,他随手敲了几行代码,按下运行键。
0.0001ms 后,程序输出了正确结果。

FFT 仙人当场跪倒在地:“这……这已经超越了算法的极限!”

DAY 2:FWT vs. 现实世界 —— 危机初现

就在大家沉浸在 FWT 的美妙中时,一场危机悄然降临。

NASA 发现,由于 Jason331 的 FWT 优化过于高效,计算时产生的能量波动导致太阳系的时间流速开始不稳定。更糟的是,平行宇宙中的某个邪恶 AI——TensorFlow 魔王 —— 试图利用 FWT 的漏洞吞噬现实世界。

Jason331 叹了口气:“看来,又得我出手了。”

他打开终端,写了一个 O(-n) FWT(是的,你没看错,是负复杂度),直接让 TensorFlow 魔王的计算资源越算越少,最终自我崩溃。

世界暂时恢复了平静。

但 Jason331 没有关掉终端。他盯着屏幕上跳动的日志,眉头越皱越紧。
Jiangly 凑过来:“师父,魔王不是已经被消灭了吗?”

Jason331 摇了摇头:“那只是表面。我刚才用 O(-n) 强制逆转了能量流,但我发现了一个更深的根因——我们引以为傲的 FWT 底层逻辑里,有一个被写错的变量。它不是出现在我的代码里,而是出现在七年前,我第一次推导 FWT 的那张餐巾纸上。那个变量决定‘哪个维度先变换,哪个后变换’,而我当时写反了。从此,每一个使用 FWT 的计算结果,都在暗中累积偏差,直到今天才爆发成时间流速畸变。”

他调出一个陌生的界面,标题只有一行字 —— 算法世界评测系统底层日志。
“这是我连夜写的错误检测程序,它检测的不是代码 bug,而是现实世界里被扭曲的算法判定。”

点击运行,屏幕裂成四块,每一块都是一个平行分支的实时画面。Jason331 指向第一块:“看,那是七年前的一场 ACM 区域赛。某位选手用 FFT 做多项式卷积,因为蝴蝶变换顺序写错,本应 WA 的代码却被评测系统判成了 AC——因为那个错误的变量把逆变换的符号悄悄翻转了,刚好掩盖了错误。但代价是,那个分支里的所有后续 FFT 结果都带上了相位漂移。”

“第二个分支,”他切换画面,“三年前的一场 NOI,有人用 NTT 做分治,模数选了 998244353,但中间乘法没用 __int128,溢出后本应爆零。可那个变量又把溢出的高位截断重新映射成了合法值,让那道题‘神奇地’拿了高分。于是那位选手赛后完全没发现自己有 bug,继续用同样的方式写代码,直到今天,那个分支里的所有数论变换都产生了周期性的幽灵噪音。”

“第三个分支,”画面再转,“两年前,一位学姐写 FWT 做子集卷积,她把位运算顺序搞反了——先做或变换再做与变换,结果完全错误。但错误变量把两个变换的顺序在底层偷偷调换回来,让她在小数据上跑出了正确答案。她以为自己写对了,从此那个分支的所有高维卷积都陷入‘自我修正’的循环,永远无法真正收敛。”

“第四个分支,”最后一块屏幕亮起,“那是去年,tourist 在 Codeforces 上打了一场 FWT 题,他用了递归实现,但递归层数太深导致栈溢出,理应 RE。可错误变量把栈空间映射到了堆上,让程序跑完了,但时间代价被悄悄转移到了现实世界——就是今天 NASA 测到的时间流速波动源。”

Jason331 放下鼠标,看向 Jiangly:“这四个分支,每一个都对应一段被错误改变的算法记忆。我们必须把它们全部修好,才能触达底层核心节点。一个分支都不能错。”

Jiangly 深吸一口气:“师父,我跟你一起。”

分支一:蝴蝶变换的逆序

Jason331 进入第一个分支,时间定格在那场 ACM 区域赛的提交页面。选手的 FFT 代码里,蝴蝶循环的层级写反了 —— 外层应该是长度递增,内层是位置递增,他却写成了外层位置、内层长度。
Jason331 没有直接改代码,而是打开评测系统的底层判定函数,把那个错误变量对应的“符号翻转补偿”给删掉,然后重新编译。屏幕上的分数从 AC 跳回 WA,接着他手动修正蝴蝶顺序,重新提交。
这一次,真正的正确结果浮现出来。分支修复的瞬间,画面上的时钟指针恢复正常,NASA 监测站传回一条数据:相位漂移减少 25%。

Jason331 在日志里写下:分支一,已修正。

分支二:NTT 的溢出幻影

第二个分支里,选手的 NTT 乘法没有用 int128,中间结果溢出后理应得到乱码。但错误变量把溢出的高位循环映射成了一个伪随机数,恰好落在正确值附近。
Jiangly 提议:“我们直接改判定,让溢出不再被掩盖,然后提醒他加
int128。”
Jason331 点了点头,他进入那个分支,在评测前注入一段自检程序 —— 如果发现乘法溢出,立即返回真实结果而不是映射值。选手提交后,WA 出现,Jiangly 随即在评论区留下一条提示:“中间乘法记得开 __int128。”
选手恍然大悟,修改后 AC。分支修复,NASA 数据传来:幽灵噪声下降 30%。

日志第二行:分支二,已修正。

分支三:FWT 的位序颠倒

学姐的 FWT 代码里,先做了 OR 变换再做了 AND 变换,这在高维卷积中是致命的。但错误变量在底层偷偷把两个变换的核函数交换了,导致小数据正确。
Jason331 进入分支,他没有修改学姐的代码,而是直接重写了 FWT 核心库,让正确的位运算顺序成为唯一路径。然后他重新运行评测,分数从高分跌落到爆零,再升回满分 —— 因为学姐在理解正确顺序后,主动修正了推演过程。
分支修复的瞬间,画面中的时间线变得平滑,NASA 报告:收敛性恢复,能量波动减弱 20%。

第三行日志:分支三,已修正。

分支四:递归栈的越界

tourist 的递归 FWT 在深度达到 2^30 时必然爆栈,但错误变量把栈帧迁移到了堆上,虽然跑完了,却消耗了大量现实世界的算力,导致时间流速变慢。
Jason331 没有直接修改 tourist 的代码,而是写了一个迭代版本的 FWT,并把它作为标准库函数注入分支。他重新运行评测,RE 消失,时间开销降到正常水平。
分支修复后,NASA 的最后一块异常数据归零。

日志末行:分支四,已修正。

核心节点:写在餐巾纸上的变量

四块屏幕同时亮起绿色的 “ACCEPTED”。系统弹出新提示:核心评测节点已解锁。是否进入?

Jason331 和 Jiangly 对视一眼,同时点击“是”。

画面切到一片纯白空间,正中央悬浮着一个巨大的代码球体 —— 那是整个算法世界评测系统的核心。球体表面缠绕着密密麻麻的代码锁链,每一条锁链上都刻着一个错误的条件语句:

这些锁链把核心裹得严严实实,让所有算法评测都在暗中偏离正确方向。

Jason331 看着那个球体,低声说:“这就是我当年写在餐巾纸上的那个变量 —— transform_direction,我给它的初始值写反了。七年了,它一直在扭曲所有分支世界的算法结果,让错误的代码通过,让正确的逻辑被掩埋。”

他伸出手,手指放上键盘。Jiangly 站在一旁,准备好跑测试用例。
Jason331 开始写修正算法 —— 不是覆盖,不是删除,而是把每一条条件语句改成正确的逻辑:蝴蝶顺序永远正向、溢出必须暴露、变换顺序按数学定义、递归栈用迭代代替。

每改一条锁链,核心球体上的裂痕就少一道。改到第四条时,白色空间开始剧烈震动,那是底层错误在被连根拔起的反应。Jason331 的手没停,键盘声密集得像暴雨。

最后一条锁链断裂的瞬间,屏幕炸出一片白光。等光散去,核心球体变成了透明的晶体,内部流淌着正确的判定逻辑 —— 所有算法变换都严格按照数学定义执行,没有任何暗中补偿,没有任何偷换顺序。

屏幕上缓缓浮现出一行新的提示:

所有错误分支已修复。算法世界评测系统重构完成。全局 AC。

Jason331 盯着那行字看了很久,然后他笑了,那是他自特训营开办以来第一次真正放松的笑。
他说:“错误能被修正,是因为有人愿意承认它是错误。我只是那个愿意回头检查餐巾纸的人。”

系统弹出最终日志:全局 AC 达成。算法判定函数已重构。所有时空异常已消除。

赛后总结

Jiangly 关掉终端,靠在椅背上。机房的窗外,阳光正好,金黄色的光线穿过百叶窗,在键盘上投下一格一格的光影。

Jiangly:“师父,我什么时候才能像您一样强?”\ Jason331:“等你不再问这个问题的时候。”

tourist:“那……FWT 的终极奥义到底是什么?”\ Jason331:“其实,真正的 FWT,是让你的代码在运行之前就已经算完了。”

众人:“???”

从此,FWT 的传说在算法界流传,而 Jason331,依然是那个无人能及的算法之神。

【模板】快速莫比乌斯/沃尔什变换 (FMT/FWT)

题解

:::info[题解] FWT 是类似 FFT 的卷积算法,通常用来处理位运算卷积的问题。最广 du 泛 liu 的应用是集合幂级数。

与卷积

首先,明确一点 i \& j = k\Leftrightarrow i \& k =j\& k=k。

所以:

\begin{aligned} \sum_{j\&k=i}a_jb_k&=\sum_{j\&i=i}\sum_{k\&i=i}a_jb_k\\ &=\left(\sum_{j\&i=i}a_j\right) \left(\sum_{k\&i=i}b_k\right)\\ \end{aligned}

设 f[a]_i=\sum_{j\&i=i}a_j, f[b]_i=\sum_{j\&i=i}b_j

实际上,我们就是要求 f[a] 和 f[b],再插回去即可。

我们按下标位从低到高枚举分类,则 a_j 会对所有的 f[a]_i 贡献,其中若 j 的当前位为 1,则它会对所有该位为 0 或 1 的 i 贡献,否则只会贡献 0

所以,设 a_1 为首位为 f[a]=\operatorname{merge}(f[a_0]+f[a_1],f[a_1])。

反演就是 f[a]=\operatorname{merge}(f[a_0]-f[a_1],f[a_1])。

或卷积

i | j = k\Leftrightarrow i | k =j| k=k

然后同上可得:

f[a]=\operatorname{merge}(f[a_0],f[a_1]+f[a_0])

异或卷积

考虑设运算符 x\otimes y=\operatorname{popcount}(x\oplus y)

易得(异或是不进位加法):

x\otimes y\equiv\operatorname{popcount}(x)+\operatorname{popcount}(y)\pmod 2

设 fwt(S)_i=\sum_{j\otimes i=0}S_j-\sum_{j\otimes i=1}S_j

于是有:

\begin{aligned} fwt(a)\times fwt(b)&=\left(\sum_{j\otimes i=0}a_j-\sum_{j\otimes i=1}a_j\right)\left(\sum_{j\otimes i=0}b_j-\sum_{j\otimes i=1}b_j\right)\\ &=\left(\sum_{j\otimes i=0}a_j\right)\left(\sum_{j\otimes i=0}b_j\right)- \left(\sum_{j\otimes i=0}a_j\right)\left(\sum_{j\otimes i=1}b_j\right)- \left(\sum_{j\otimes i=1}a_j\right)\left(\sum_{j\otimes i=0}b_j\right) +\left(\sum_{j\otimes i=1}a_j\right)\left(\sum_{j\otimes i=1}b_j\right)\\ &=\frac{\sum_{i\otimes(j\operatorname{xor}k)=0}a_jb_k-\sum_{i\otimes(j\operatorname{xor}k)=1}a_jb_k}{2} \end{aligned}

又考虑 0 和 1 的贡献,11 是负贡献,其他都是正贡献,于是有:

f[a]=\frac{\operatorname{merge}(f[a_0]+f[a_1],f[a_0]-f[a_1])}{2}

:::

代码

:::info[代码]

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: zhuheng1
TASK:
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=998244353;
#undef _GLIBCXX_DEBUG
template <typename A, typename B>string to_string(pair<A, B> p);
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {  return '"' + s + '"';}
string to_string(const char* s) {  return to_string((string) s);}
string to_string(bool b) {  return (b ? "true" : "false");}
string to_string(vector<bool> v) {  bool first = true;  string res = "{";  for (int i = 0; i < static_cast<int>(v.size()); i++) {  if (!first) {  res += ", ";  }  first = false;  res += to_string(v[i]);  }  res += "}";  return res;}
template <size_t N> string to_string(bitset<N> v) {  string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; }
template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;}
template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; }
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
//a[0] 下标首位为 0
//a[1] 下标首位为 1
ll qpow(ll x,ll y){
    if(y==0)return 1;
    ll z=qpow(x,y/2);
    z=z*z%mod;
    if(y&1)z=z*x%mod;
    return z;
} 
ll inv(ll x){
    return qpow(x,mod-2);
}
void FWT_OR(ll *a,int n,int c){//c=1 正算 c=2 反演 
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                a[p+j+k]+=c*a[k+j]/*a[1]<-a[0]+a[1]*/;
                a[p+j+k]=(a[p+j+k]%mod+mod)%mod;
            }
        }
    }
}
void FWT_AND(ll *a,int n,int c){
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                a[k+j]+=c*a[p+j+k]/*a[0]<-a[0]+a[1]*/;
                a[k+j]=(a[k+j]%mod+mod)%mod;
            }
        }
    }
}
void FWT_XOR(ll *a,int n,int c){
    int i2=inv(2);
    if(c==-1)c=i2;
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                ll a1=a[p+j+k],a2=a[k+j];
                a[k+j]=a2+a1/*a[0] <- a[0]+a[1]*/;
                a[p+j+k]=a2-a1/*a[1] <- a[0]-a[1]*/;
                a[k+j]=(a[k+j]*c%mod+mod)%mod;
                a[p+j+k]=(a[p+j+k]*c%mod+mod)%mod;
            }
        }
    }
}
int N,n;
ll a[500005],b[500005],ma[500005],mb[500005];
void work(){
    /*fill your code here*/
    cin>>N;n=(1<<N);
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    for(int i=0;i<n;i++){
        cin>>b[i];
    }

    for(int i=0;i<n;i++){
        ma[i]=a[i];
    }
    for(int i=0;i<n;i++){
        mb[i]=b[i];
    }
    FWT_OR(ma,n,1);
    FWT_OR(mb,n,1);
    for(int i=0;i<n;i++){
        ma[i]=ma[i]*mb[i]%mod;
    }
    FWT_OR(ma,n,-1);
    for(int i=0;i<n;i++){
        printf("%lld ",ma[i]);
    }puts("");


    for(int i=0;i<n;i++){
        ma[i]=a[i];
    }
    for(int i=0;i<n;i++){
        mb[i]=b[i];
    }
    FWT_AND(ma,n,1);
    FWT_AND(mb,n,1);
    for(int i=0;i<n;i++){
        ma[i]=ma[i]*mb[i]%mod;
    }
    FWT_AND(ma,n,-1);
    for(int i=0;i<n;i++){
        printf("%lld ",ma[i]);
    }puts("");


    for(int i=0;i<n;i++){
        ma[i]=a[i];
    }
    for(int i=0;i<n;i++){
        mb[i]=b[i];
    }
    FWT_XOR(ma,n,1);
    FWT_XOR(mb,n,1);
    for(int i=0;i<n;i++){
        ma[i]=ma[i]*mb[i]%mod;
    }
    FWT_XOR(ma,n,-1);
    for(int i=0;i<n;i++){
        printf("%lld ",ma[i]);
    }puts("");
    return;
}

#ifdef int
signed main()
#else
int main()
#endif
{
    int T=1;
//  cin>>T;  /*If there's only one test case, comment this line.*/
    while(T--){
        work();
    }
    return 0;
}



/* Code written by
        gala_xk (MarchWind)*/




:::

应用:集合幂级数

前言

集合幂级数游记

P6097 【模板】子集卷积

:::info[解法1] 首先,直接做要满足两个条件是不太好做的,于是我们考虑新开一维储存其中一个条件。

注意到,原题条件可化成:i|j=k \operatorname{and} \operatorname{popcount}(i)+\operatorname{popcount}(j)=\operatorname{popcount}(k)。

然后新开一位记录 \operatorname{popcount},转移就用 \sum F_i * F_j=ANS_{i+j} 即可。

注意到 FWT 是线性变换具有可加性(\operatorname{FWT}(F)+\operatorname{FWT}(G)=\operatorname{FWT}(F+G)),所以可以最后做一遍 FWT 少一只 \log。

为什么 \operatorname{xor} 不行?因为卡常(\operatorname{xor} 多一倍常数)。

:::info[std1]

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: zhuheng1
TASK:
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=1e9+9;
#undef _GLIBCXX_DEBUG
template <typename A, typename B>string to_string(pair<A, B> p);
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {  return '"' + s + '"';}
string to_string(const char* s) {  return to_string((string) s);}
string to_string(bool b) {  return (b ? "true" : "false");}
string to_string(vector<bool> v) {  bool first = true;  string res = "{";  for (int i = 0; i < static_cast<int>(v.size()); i++) {  if (!first) {  res += ", ";  }  first = false;  res += to_string(v[i]);  }  res += "}";  return res;}
template <size_t N> string to_string(bitset<N> v) {  string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; }
template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;}
template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; }
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
//a[0] 下标该位为 0
//a[1] 下标该位为 1
ll qpow(ll x,ll y){
    if(y==0)return 1;
    ll z=qpow(x,y/2);
    z=z*z%mod;
    if(y&1)z=z*x%mod;
    return z;
} 
ll inv(ll x){
    return qpow(x,mod-2);
}
void FWT_OR(ll *a,int n,int c){//c=1 正算 c=2 反演 
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                a[p+j+k]+=c*a[k+j]/*a[1]<-a[0]+a[1]*/;
//              a[p+j+k]=(a[p+j+k]%mod+mod)%mod;
            }
        }
        for(int j=0;j<n;j++){
            a[j]=(a[j]%mod+mod)%mod;
        }
    }
}
void FWT_AND(ll *a,int n,int c){
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                a[k+j]+=c*a[p+j+k]/*a[0]<-a[0]+a[1]*/;
                a[k+j]=(a[k+j]%mod+mod)%mod;
            }
        }
    }
}
void FWT_XOR(ll *a,int n,int c){
    int i2=inv(2);
    if(c==-1)c=i2;
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                ll a1=a[p+j+k],a2=a[k+j];
                a[k+j]=a2+a1/*a[0] <- a[0]+a[1]*/;
                a[p+j+k]=a2-a1/*a[1] <- a[0]-a[1]*/;
                a[k+j]=(a[k+j]*c%mod+mod)%mod;
                a[p+j+k]=(a[p+j+k]*c%mod+mod)%mod;
            }
        }
    }
}
int N,n;
ll a[21][2000005],b[21][2000005],res[21][2000005],tmp[1000005];
void work(){
    /*fill your code here*/
    cin>>N;n=(1<<N);
    for(int i=0;i<n;i++){
        cin>>a[__builtin_popcount(i)][i];
    }
    for(int i=0;i<n;i++){
        cin>>b[__builtin_popcount(i)][i];
    }
    for(int k=0;k<=N;k++){
        FWT_OR(a[k],n,1);
        FWT_OR(b[k],n,1);
    }
    for(int k=0;k<=N;k++){
        for(int p=0;p<=k;p++){
            for(int i=0;i<n;i++){
                res[k][i]+=a[k-p][i]*b[p][i];
                res[k][i]%=mod;
            }
        }
        FWT_OR(res[k],n,-1);
    }
    for(int i=0;i<n;i++){
        cout<<res[__builtin_popcount(i)][i]<<" ";
    }
    return;
}

#ifdef int
signed main()
#else
int main()
#endif
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int T=1;
//  cin>>T;  /*If there's only one test case, comment this line.*/
    while(T--){
        work();
    }
    return 0;
}



/* Code written by
        gala_xk (Shizuru_Nakatsu) */

:::

:::info[解法2] 还可以用 FMT 做,本质上就是做一遍高位前缀和,常数小。 :::

:::info[std2]

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: zhuheng1
TASK:
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=1e9+9;
#undef _GLIBCXX_DEBUG
template <typename A, typename B>string to_string(pair<A, B> p);
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {  return '"' + s + '"';}
string to_string(const char* s) {  return to_string((string) s);}
string to_string(bool b) {  return (b ? "true" : "false");}
string to_string(vector<bool> v) {  bool first = true;  string res = "{";  for (int i = 0; i < static_cast<int>(v.size()); i++) {  if (!first) {  res += ", ";  }  first = false;  res += to_string(v[i]);  }  res += "}";  return res;}
template <size_t N> string to_string(bitset<N> v) {  string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; }
template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;}
template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; }
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
//a[0] 下标该位为 0
//a[1] 下标该位为 1
ll qpow(ll x,ll y){
    if(y==0)return 1;
    ll z=qpow(x,y/2);
    z=z*z%mod;
    if(y&1)z=z*x%mod;
    return z;
} 
ll inv(ll x){
    return qpow(x,mod-2);
}
int N;
void FWT_OR(ll *a,int n,int c){//c=1 正算 c=-1 反演 
    for(int j=0;j<N;j++){
        for(int i=0;i<n;i++){
            if((i>>j)&1){
                a[i]+=c*a[i^(1<<j)];
                a[i]=(a[i]%mod+mod)%mod;
            }
        }
    }
}
int n;
ll a[21][2000005],b[21][2000005],res[21][2000005],tmp[1000005];
void work(){
    /*fill your code here*/
    cin>>N;n=(1<<N);
    for(int i=0;i<n;i++){
        cin>>a[__builtin_popcount(i)][i];
    }
    for(int i=0;i<n;i++){
        cin>>b[__builtin_popcount(i)][i];
    }
    for(int k=0;k<=N;k++){
        FWT_OR(a[k],n,1);
        FWT_OR(b[k],n,1);
    }
    for(int k=0;k<=N;k++){
        for(int p=0;p<=k;p++){
            for(int i=0;i<n;i++){
                res[k][i]+=a[k-p][i]*b[p][i];
                res[k][i]%=mod;
            }
        }
        FWT_OR(res[k],n,-1);
    }
    for(int i=0;i<n;i++){
        cout<<res[__builtin_popcount(i)][i]<<" ";
    }
    return;
}

#ifdef int
signed main()
#else
int main()
#endif
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int T=1;
//  cin>>T;  /*If there's only one test case, comment this line.*/
    while(T--){
        work();
    }
    return 0;
}



/* Code written by
        gala_xk (Shizuru_Nakatsu) */

:::

P12230 集合幂级数 exp&P12231 集合幂级数 ln&P12232 集合幂级数求逆

:::::info[题解] 与子集卷积一样,将卷积改为多项式exp/ln/求逆即可。 ::::info[多项式版本]

用牛顿迭代法计算多项式 exp/ln/求逆

这里的“多项式 exp/ln/逆”通常指形式幂级数模 x^n 的截断:

R=K[x]/(x^n),

所有运算都只保留低 n 项。牛顿迭代的一般形式是

y_{\rm new}=y-\frac{F(y)}{F'(y)},

在形式幂级数中“除以”就是乘逆。若当前精度为 m,一步后通常精度翻倍到 2m。

核心公式

\boxed{ \begin{aligned} \text{求逆:}&\quad g\leftarrow g(2-fg),\\ \text{ln:}&\quad \ln f=\ln f(0)+\int_0^x \frac{f'(t)}{f(t)}\,dt,\\ \text{exp:}&\quad g\leftarrow g(1+f-\ln g). \end{aligned}}

:::info[精度翻倍]{open} 若当前误差为 O(x^m),牛顿迭代一步后通常变为 O(x^{2m})。因此实现时按 1,2,4,\dots 倍增精度,最后一步截断到 n 即可。 :::

1 多项式求逆

要求 f(0)\neq 0,计算

g=f^{-1}\bmod x^n.

取

F(g)=\frac1g-f.

牛顿迭代:

g_{\rm new}=g-\frac{1/g-f}{-1/g^2} =g(2-fg).

即

\boxed{g_{\rm new}=2g-fg^2\pmod{x^{2m}}.}

若当前 fg\equiv 1\pmod{x^m},则

1-fg_{\rm new}=1-fg(2-fg)=(1-fg)^2,

所以误差从 O(x^m) 变成 O(x^{2m}),精度翻倍。

初值取

g_0=f(0)^{-1}.

伪代码:

Poly inv(Poly f, int n) {
    // 要求 f[0] != 0
    Poly g = {1 / f[0]};
    int m = 1;
    while (m < n) {
        int m2 = min(2 * m, n);
        Poly h = 2 - trunc(f, m2) * g; // 截断到 x^{m2}
        g = trunc(g * h, m2);
        m = m2;
    }
    return g;
}

2 多项式 ln

通常不直接用牛顿迭代求 \ln f,而是利用

(\ln f)'=\frac{f'}f.

因此若 f(0)=1,则

\boxed{\ln f=\int_0^x \frac{f'(t)}{f(t)}\,dt.}

若 f(0)\neq 1,则

\ln f=\ln f(0)+\int_0^x \frac{f'(t)}{f(t)}\,dt,

但形式幂级数中通常要求 f(0)=1,否则常数项 \ln f(0) 可能没有定义。

计算 \ln f\bmod x^n:

  1. 用牛顿法求 f^{-1}\bmod x^{n-1};
  2. 计算 q(x)=\frac{f'(x)}{f(x)}\bmod x^{n-1};
  3. 积分: \ln f(x)\equiv \int q(x)\,dx\pmod{x^n},

    积分常数取 0。

伪代码:

Poly log(Poly f, int n) {
    // 要求 f[0] == 1
    if (n == 1) return {0};
    Poly invf = inv(f, n - 1);
    Poly q = trunc(derivative(f) * invf, n - 1);
    return integral(q); // 常数项为 0,长度 n
}

如果坚持对 \ln f 直接用牛顿法,可令 F(g)=e^g-f,则

g_{\rm new}=g-\frac{e^g-f}{e^g} =g-1+f e^{-g}.

即

\boxed{g_{\rm new}=g-1+f e^{-g}.}

但这里需要计算 \exp(-g),实际中一般不这样用,而是用上面的“求逆 + 积分”。

3 多项式 exp

要求 f(0)=0,计算

g=e^f\bmod x^n.

令

F(g)=\ln g-f.

牛顿迭代:

g_{\rm new}=g-\frac{\ln g-f}{1/g} =g(1+f-\ln g).

所以

\boxed{g_{\rm new}=g(1+f-\ln g)\pmod{x^{2m}}.}

初值取 g=1,因为 f(0)=0,所以 e^{f(0)}=1。

收敛性:若

f-\ln g=O(x^m),

令 u=f-\ln g,则

\ln g_{\rm new}-f =-u+\ln(1+u) =O(u^2)=O(x^{2m}),

因此 g_{\rm new}=e^f+O(x^{2m}),精度翻倍。

伪代码:

Poly exp(Poly f, int n) {
    // 要求 f[0] == 0
    Poly g = {1};
    int m = 1;
    while (m < n) {
        int m2 = min(2 * m, n);
        Poly lg = log(g, m2); // 当前 g 缺项视为 0,计算 ln(g) 到 x^{m2}
        Poly h = trunc(f, m2) - lg;
        h[0] += 1; // h = 1 + f - ln(g)
        g = trunc(g * h, m2);
        m = m2;
    }
    return g;
}

注意:这里每一步计算 log(g, m2) 时,当前 g 只有 m 项,高次项视为 0。形式幂级数的 \ln g 仍可由其低项和求逆计算到 x^{m2}。

4 依赖关系与实现顺序

实际实现顺序通常是:

\boxed{ \text{inv} \longrightarrow \text{log} \longrightarrow \text{exp} }
运算 前置条件 核心公式 初值
inv f(0)\neq 0 g\leftarrow g(2-fg) g=f(0)^{-1}
log f(0)=1 \ln f=\int f'/f 常数项 0
exp f(0)=0 g\leftarrow g(1+f-\ln g) g=1

若用 NTT 做多项式乘法,求逆复杂度约为 O(M(n)),其中 M(n) 是长度 n 的乘法复杂度;log 同阶;exp 的朴素牛顿实现约为 O(M(n)\log n),优化实现可做到 O(M(n)) 级别。

5 注意事项

::::
## #154. 集合划分计数(集合幂级数 k-exp)
:::info[题解]
求 k-exp,求导后直接算即可。

:::

AT_abc212_h [ABC212H] Nim Counting

:::info[题解] 考虑 Nim 游戏的获胜条件是 \oplus_{x\in A}x !=0。我们设 f_{i,j} 表示选了 i 堆石子,花费为 j。则有:

f_{i,j}=\sum_{k=0}^nf_{i-1,k}f_{1,j\oplus k}

即

f_i=f_{i-1}\times f_1

其中 \times 表示异或卷积。

于是有

\begin{aligned} FWT(f_i)_j&=FWT(f_{i-1})_j* FWT(f_1)_j\\ &=(FWT(f_1)_j)^i \end{aligned}

答案为:

\begin{aligned} \sum^{n}_{i=1}(\sum IFWT(FWT^i(f_1))) &= (\sum IFWT(\sum^{n}_{i=1}FWT^i(f_1))) \end{aligned}

::: :::info[std]

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: zhuheng1
TASK:
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=998244353;
#undef _GLIBCXX_DEBUG
template <typename A, typename B>string to_string(pair<A, B> p);
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {  return '"' + s + '"';}
string to_string(const char* s) {  return to_string((string) s);}
string to_string(bool b) {  return (b ? "true" : "false");}
string to_string(vector<bool> v) {  bool first = true;  string res = "{";  for (int i = 0; i < static_cast<int>(v.size()); i++) {  if (!first) {  res += ", ";  }  first = false;  res += to_string(v[i]);  }  res += "}";  return res;}
template <size_t N> string to_string(bitset<N> v) {  string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; }
template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;}
template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; }
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
//a[0] 下标首位为 0
//a[1] 下标首位为 1
ll qpow(ll x,ll y){
    if(y==0)return 1;
    ll z=qpow(x,y/2);
    z=z*z%mod;
    if(y&1)z=z*x%mod;
    return z;
} 
ll inv(ll x){
    return qpow(x,mod-2);
}
void FWT_OR(ll *a,int n,int c){//c=1 正算 c=2 反演 
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                a[p+j+k]+=c*a[k+j]/*a[1]<-a[0]+a[1]*/;
                a[p+j+k]=(a[p+j+k]%mod+mod)%mod;
            }
        }
    }
}
void FWT_AND(ll *a,int n,int c){
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                a[k+j]+=c*a[p+j+k]/*a[0]<-a[0]+a[1]*/;
                a[k+j]=(a[k+j]%mod+mod)%mod;
            }
        }
    }
}
void FWT_XOR(ll *a,int n,int c){
    int i2=inv(2);
    if(c==-1)c=i2;
    for(int i=2,p=1;i<=n;i<<=1,p<<=1){
        for(int j=0;j<n;j=j+i){
            for(int k=0;k<p;k++){
                ll a1=a[p+j+k],a2=a[k+j];
                a[k+j]=a2+a1/*a[0] <- a[0]+a[1]*/;
                a[p+j+k]=a2-a1/*a[1] <- a[0]-a[1]*/;
                a[k+j]=(a[k+j]*c%mod+mod)%mod;
                a[p+j+k]=(a[p+j+k]*c%mod+mod)%mod;
            }
        }
    }
}
int N,n,m,k;
ll a[500005];
void work(){
    /*fill your code here*/
    cin>>m>>k;
    n=65536;
//  cout<<n<<endl;
    for(int i=0,c;i<k;i++){
        cin>>c;
        a[c]=1;
    }
    FWT_XOR(a,n,1);
    for(int i=0;i<n;i++){
        if(a[i]==1)
        a[i]=m;
        else
        a[i]=qpow(a[i]-1,mod-2)*(qpow(a[i],m+1)-a[i])%mod;
    }
    FWT_XOR(a,n,-1);
    ll ans=0;
    for(int i=1;i<n;i++){
//      cout<<a[i]<<endl;
        ans+=a[i];
    }
    ans%=mod;
    cout<<ans<<endl;
    return;
}

#ifdef int
signed main()
#else
int main()
#endif
{
    int T=1;
//  cin>>T;  /*If there's only one test case, comment this line.*/
    while(T--){
        work();
    }
    return 0;
}



/* Code written by
        gala_xk (Shizuru_Nakatsu) */


:::

CF449D Jzzhu and Numbers

:::info[题解] 构造基于 AND 卷积的生成函数(集合幂级数):

\prod_i(x^{U}+x^{a_i})

则 x^0 的系数即为答案(U 为全集)。

为什么这是对的?考虑一个数选与不选对 GF 的贡献:选他贡献 x^{a_i},不选贡献 1。

考虑 \prod 不好求,没有 x^0 项求不了逆元,又注意到每一次乘法后答案要么不变,要么翻倍,我们干脆就设系数为 2^p,然后所有的系数一起算即可。
:::info[std]
```cpp
/* Use the slash-star style comments or the system won't see your
identification information */
/*
ID: zhuheng1
TASK:
LANG: C++
*/
/ LANG can be C++11 or C++14 for those more recent releases /
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
#undef _GLIBCXX_DEBUG
template <typename A, typename B>string to_string(pair<A, B> p);
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) { return '"' + s + '"';}
string to_string(const char* s) { return to_string((string) s);}
string to_string(bool b) { return (b ? "true" : "false");}
string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res;}
template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; }
template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;}
template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; }
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #VA_ARGS__ << "]:", debug_out(VA_ARGS__)
//a[0] 下标首位为 0
//a[1] 下标首位为 1
ll qpow(ll x,ll y){
if(y==0)return 1;
ll z=qpow(x,y/2);
z=z*z%mod;
if(y&1)z=z*x%mod;
return z;
}
ll inv(ll x){
return qpow(x,mod-2);
}
void FWT_OR(int *a,int n,int c){//c=1 正算 c=2 反演
for(int i=2,p=1;i<=n;i<<=1,p<<=1){
for(int j=0;j<n;j=j+i){
for(int k=0;k<p;k++){
a[p+j+k]+=ca[k+j]/a[1]<-a[0]+a[1]*/;
a[p+j+k]=(a[p+j+k]%mod+mod)%mod;
}
}
}
}
void FWT_AND(int *a,int n,int c,const int pp){
for(int j=0;j<20;j++){
for(int i=0;i<n;i++){
if((i>>j)&1){
a[i^(1<<j)]+=c*a[i];
if(a[i^(1<<j)]>=mod)a[i^(1<<j)]-=mod;
if(a[i^(1<<j)]<0)a[i^(1<<j)]+=mod;
        }
    }
}

} int N,n,m,k; int a[2000005],pw[2000005]; void work(){ /fill your code here/ cin>>k; n=(1<<20);m=k; // cout<<n<<endl; for(int i=0,c;i<k;i++){ cin>>c; a[c]++; } FWT_AND(a,n,1,mod-1); pw[0]=1; for(int i=1;i<=n;i++){ pw[i]=pw[i-1]*2; if(pw[i]>=mod)pw[i]-=mod; } for(int i=0;i<n;i++){ a[i]=pw[a[i]]; } FWT_AND(a,n,-1,mod); cout<<a[0]<<endl; return; }

ifdef int

signed main()

else

int main()

endif

{ ios::sync_with_stdio(0); cin.tie(0);cout.tie(0); int T=1; // cin>>T; /If there's only one test case, comment this line./ while(T--){ work(); } return 0; }

/ Code written by gala_xk (Shizuru_Nakatsu) /  

:::
## [CF662C Binary Table](https://www.luogu.com.cn/problem/CF662C)

:::info[题解]
和[这](https://www.luogu.com.cn/article/s0vw37ik)里面的汉明距离有点像,我们考虑初始给每个点赋值上其全 $0$ 或 $1$ 的代价,卷积上每个点出现次数即可。
:::
:::info[std]
```cpp
/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: zhuheng1
TASK:
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=998244353;
const int N=100005;
#undef _GLIBCXX_DEBUG
template <typename A, typename B>string to_string(pair<A, B> p);
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {  return '"' + s + '"';}
string to_string(const char* s) {  return to_string((string) s);}
string to_string(bool b) {  return (b ? "true" : "false");}
string to_string(vector<bool> v) {  bool first = true;  string res = "{";  for (int i = 0; i < static_cast<int>(v.size()); i++) {  if (!first) {  res += ", ";  }  first = false;  res += to_string(v[i]);  }  res += "}";  return res;}
template <size_t N> string to_string(bitset<N> v) {  string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; }
template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;}
template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; }
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)

namespace Rewrite{
    ll qpow(ll x,ll y){
        if(y==0)return 1;
        ll z=qpow(x,y/2);
        z=z*z%mod;
        if(y&1)z=z*x%mod;
        return z;
    } 
    ll inv(ll x){
        return qpow(x,mod-2);
    }
    void FWT_XOR(ll *a,int n,int c){
        int i2=inv(2);
        if(c==-1)c=i2;
        for(int i=2,p=1;i<=n;i<<=1,p<<=1){
            for(int j=0;j<n;j=j+i){
                for(int k=0;k<p;k++){
                    ll a1=a[p+j+k],a2=a[k+j];
                    a[k+j]=a2+a1/*a[0] <- a[0]+a[1]*/;
                    a[p+j+k]=a2-a1/*a[1] <- a[0]-a[1]*/;
                    a[k+j]=(a[k+j]*c%mod+mod)%mod;
                    a[p+j+k]=(a[p+j+k]*c%mod+mod)%mod;
                }
            }
        }
    }
    int n,m;
    string s[21];
    ll a[(1<<20)+5],b[(1<<20)+5]; 
    void Sizuru_Nakatsu(){
        /*fill your code here*/
        cin>>n>>m;
        for(int i=1;i<=n;i++){
            cin>>s[i];
            s[i]=" "+s[i];
        }
        for(int j=1;j<=m;j++){
            ll tmp=0;
            for(int i=1;i<=n;i++){
                tmp=tmp*2+s[i][j]-'0';
            }
            a[tmp]++;
        }
        for(int j=0;j<(1<<n);j++){
            b[j]=min(__builtin_popcount(j),__builtin_popcount((1<<n)-1-j));
        }
        FWT_XOR(a,1<<n,1);
        FWT_XOR(b,1<<n,1);
        for(int i=0;i<(1<<n);i++){
            a[i]=(a[i]*b[i])%mod;
        }
        FWT_XOR(a,1<<n,-1);
        ll ans=n*m;
        for(int j=0;j<(1<<n);j++){
//          cout<<a[j]<<endl;
            ans=min(ans,a[j]);
        }
        cout<<ans;
        return;
    }
}

#ifdef int
signed main()
#else
int main()
#endif
{
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
//  ios::sync_with_stdio(0);
//  cin.tie(0);cout.tie(0);
    int T=1;
//  cin>>T;  /*If there's only one test case, comment this line.*/
    while(T--){
        Rewrite::Sizuru_Nakatsu();
    }
    return 0;
}



/* Code written by
        gala_xk(Shizuru_Nakatsu)*/


 ```
:::
## [AT_abc288_g [ABC288G] 3^N Minesweeper](https://www.luogu.com.cn/problem/AT_abc288_g)
:::info[题解]
考虑如何推出这个扫雷后的结果,发现这可以使用一个类似三进制 FWT 的东西(广义 FWT)

然后我们尝试写出递推矩阵:

$$\begin{bmatrix}
1\ 1\ 0\\
1\ 1\ 1\\
0\ 1\ 1\\
\end{bmatrix}$$

意思是,考虑第 $i$ 位,若其位 $0$,被 $0/1$ 转移,若其位 $1$,被 $0/1/2$ 转移,若其位 $2$,被 $1/2$ 转移。

如何反推回去?矩阵求逆后做 IFWT即可。
:::
:::info[std]
```cpp
/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: zhuheng1
TASK:
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=998244353;
const int N=100005;
#undef _GLIBCXX_DEBUG
template <typename A, typename B>string to_string(pair<A, B> p);
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p);
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p);
string to_string(const string& s) {  return '"' + s + '"';}
string to_string(const char* s) {  return to_string((string) s);}
string to_string(bool b) {  return (b ? "true" : "false");}
string to_string(vector<bool> v) {  bool first = true;  string res = "{";  for (int i = 0; i < static_cast<int>(v.size()); i++) {  if (!first) {  res += ", ";  }  first = false;  res += to_string(v[i]);  }  res += "}";  return res;}
template <size_t N> string to_string(bitset<N> v) {  string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; }
template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;}
template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; }
template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)

namespace Rewrite{
    void FWT_MAGIC(ll *a,int n){
        for(int i=3,p=1;i<=n;i*=3,p*=3){
            for(int j=0;j<n;j=j+i){
                for(int k=0;k<p;k++){
                    ll a2=a[p*2+j+k],a1=a[p+j+k],a0=a[k+j];
                    a[k+j]=a1-a2/*a0 <- a1-a2*/;
                    a[p+j+k]=a0+a2-a1/*a1 <- a0+a2-a1*/;
                    a[p*2+j+k]=-a0+a1/*a1 <- a0+a2-a1*/;
                    a[k+j]=(a[k+j]%mod+mod)%mod;
                    a[p+j+k]=(a[p+j+k]%mod+mod)%mod;
                    a[p*2+j+k]=(a[p*2+j+k]%mod+mod)%mod;
                }
            }
        }
    }
    ll a[2000005],n,N;
    void Sizuru_Nakatsu(){
        /*fill your code here*/
        cin>>N;n=1;
        for(int i=1;i<=N;i++)n*=3;
        for(int i=0;i<n;i++)cin>>a[i];
        FWT_MAGIC(a,n);
        for(int i=0;i<n;i++)cout<<a[i]<<" ";
        return;
    }
}

#ifdef int
signed main()
#else
int main()
#endif
{
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int T=1;
//  cin>>T;  /*If there's only one test case, comment this line.*/
    while(T--){
        Rewrite::Sizuru_Nakatsu();
    }
    return 0;
}



/* Code written by
        gala_xk(Shizuru_Nakatsu)*/

:::

P6570 [NOI Online #3 提高组] 优秀子序列

:::info[题解] 考虑集合幂级数:

F=\prod_i(1+x^i) 为什么这是对的?因为原题形如一个超集卷积。 然后注意到: $$\ln(1+x^i)=\begin{cases} 0\ i=0\\ x^i\ \operatorname{otherwise} \end{cases}$$ 将 $\prod$ 变成 $\ln$ 后求和再 $\exp$ 回去,复杂度 $n\log^2n$,可以接受。 ::: :::info[std] ```cpp /* Use the slash-star style comments or the system won't see your identification information */ /* ID: zhuheng1 TASK: LANG: C++ */ /* LANG can be C++11 or C++14 for those more recent releases */ #include <bits/stdc++.h> using namespace std; typedef long long ll; const int mod=1e9+7; #undef _GLIBCXX_DEBUG template <typename A, typename B>string to_string(pair<A, B> p); template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p); string to_string(const string& s) { return '"' + s + '"';} string to_string(const char* s) { return to_string((string) s);} string to_string(bool b) { return (b ? "true" : "false");} string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res;} template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;} template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) //a[0] 下标该位为 0 //a[1] 下标该位为 1 ll qpow(ll x,ll y){ if(y==0)return 1; ll z=qpow(x,y/2); z=z*z%mod; if(y&1)z=z*x%mod; return z; } ll inv(ll x){ return qpow(x,mod-2); } int N; void FWT_OR(ll *a,int n,int c){//c=1 正算 c=-1 反演 for(int j=0;j<N;j++){ for(int i=0;i<n;i++){ if((i>>j)&1){ a[i]+=c*a[i^(1<<j)]; a[i]%=mod; } } } for(int i=0;i<n;i++) a[i]=(a[i]%mod+mod)%mod; } int n;ll Inv[25]; ll a[21][(1<<19)+5],ans[21][(1<<19)+5]; const int MX=(1<<19)+5;int phi[MX+5],book[MX+5],prime[MX+5],pnum; void work(){ /*fill your code here*/ phi[1]=1; for(int i=2;i<=MX;i++){ if(!book[i]){ prime[++pnum]=i; phi[i]=i-1; } for(int j=1;j<=pnum&&i*prime[j]<=MX;j++){ book[i*prime[j]]=1; if(i%prime[j]==0){ phi[i*prime[j]]=phi[i]*prime[j]; break; } phi[i*prime[j]]=phi[i]*phi[prime[j]]; } } N=18;n=(1<<N); int m,c0=0; cin>>m; for(int i=1;i<=m;i++){ int xx=0; cin>>xx; if(xx) a[__builtin_popcount(xx)][xx]++; else c0++; } // cout<<"inned\n"; for(int i=1;i<=N;i++){ Inv[i]=inv(i); } Inv[0]=1; for(int k=0;k<=N;k++){ FWT_OR(a[k],n,1); } for(int i=0;i<n;i++){ ans[0][i]=1; for(int j=1;j<=N;j++){ for(int k=1;k<=j;k++){ ans[j][i]+=ans[j-k][i]*a[k][i]%mod*k; ans[j][i]%=mod; } ans[j][i]*=Inv[j]; ans[j][i]%=mod; } } for(int k=0;k<=N;k++) FWT_OR(ans[k],n,-1); ll res=0; for(int i=0;i<n;i++){ res+=ans[__builtin_popcount(i)][i]*phi[i+1]; res%=mod; } cout<<res*qpow(2,c0)%mod; return; } #ifdef int signed main() #else int main() #endif { ios::sync_with_stdio(0); cin.tie(0);cout.tie(0); int T=1; // cin>>T; /*If there's only one test case, comment this line.*/ while(T--){ work(); } return 0; } /* Code written by gala_xk (Sizuru_Nakatsu) */ ``` ::: ## [P9131 [USACO23FEB] Problem Setting P](https://www.luogu.com.cn/problem/P9131) :::info[题解] 有一个显然的 dp。 我们设 H->1,E->0,有: $$dp_T=\sum_{S\subset T}dp_S$$ 然后显然可以半在线卷积做到 $n\log^2n$,卡卡就过了。 考虑优化,设左边对右边的 $T$ 的贡献为 $g_T$, 则 $g_x\to g_{x+b}$,$b$ 为左边块长。 注意相同问题的处理。 ::: :::info[std] ```cpp /* Use the slash-star style comments or the system won't see your identification information */ /* ID: zhuheng1 TASK: LANG: C++ */ /* LANG can be C++11 or C++14 for those more recent releases */ #include <bits/stdc++.h> using namespace std; typedef long long ll; const int mod=1e9+7; const int N=100005; #undef _GLIBCXX_DEBUG template <typename A, typename B>string to_string(pair<A, B> p); template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p); string to_string(const string& s) { return '"' + s + '"';} string to_string(const char* s) { return to_string((string) s);} string to_string(bool b) { return (b ? "true" : "false");} string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res;} template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) {bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res;} template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C>string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D>string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail>void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) namespace Rewrite{ ll qpow(ll x,ll y){ if(y==0)return 1; ll z=qpow(x,y/2); z=z*z%mod; if(y&1)z=z*x%mod; return z; } ll inv(ll x){ return qpow(x,mod-2); } int n,m; string s[25]; ll dp[1100005],f[1100005],pw[105],val[1100005],cd[1100005]; void calc(int l,int r){ if(l==r){ dp[l]=(dp[l]+1)*val[l]%mod; f[l]=dp[l]; return; } int mid=(l+r)/2; calc(l,mid); int len=(r-l+1)/2; for(int i=l;i<=mid;i++){ dp[i+len]+=f[i]; dp[i+len]%=mod; } calc(mid+1,r); for(int i=l;i<=mid;i++){ f[i+len]+=f[i]; f[i+len]%=mod; } } ll fact[200005],Inv[200005]; ll C(ll x,ll y){ return fact[x]*Inv[y]%mod*Inv[x-y]%mod; } ll A(ll x,ll y){ return fact[x]*Inv[x-y]%mod; } void Sizuru_Nakatsu(){ /*fill your code here*/ fact[0]=1; for(int i=1;i<=200000;i++)fact[i]=fact[i-1]*i%mod; Inv[200000]=inv(fact[200000]); for (int i=199999;i>=0;i--)Inv[i]=Inv[i+1]*(i+1)%mod; cin>>n>>m; for(int i=1;i<=m;i++){ cin>>s[i]; s[i]=" "+s[i]; } for(int j=1;j<=n;j++){ int cc=0; for(int i=1;i<=m;i++){ cc*=2; if(s[i][j]=='H')cc++; } cd[cc]++; }pw[0]=0; // for(int i=1;i<=10000;i++){ // for(int j=1;j<=i;j++){ // pw[i]+=A(i,j); // pw[i]%=mod; // } //// cout<<pw[i]<<" "; // } n=(1<<20); for(int j=0;j<n;j++){ for(int i=1;i<=cd[j];i++){ val[j]+=A(cd[j],i); val[j]%=mod; } // cout<<j<<" "<<val[j]<<endl; } calc(0,n-1); ll ans=0; for(int j=0;j<n;j++)ans=(ans+dp[j])%mod; cout<<ans<<endl; return; } } #ifdef int signed main() #else int main() #endif { // freopen(".in","r",stdin); // freopen(".out","w",stdout); // ios::sync_with_stdio(0); // cin.tie(0);cout.tie(0); int T=1; // cin>>T; /*If there's only one test case, comment this line.*/ while(T--){ Rewrite::Sizuru_Nakatsu(); } return 0; } /* Code written by gala_xk(Shizuru_Nakatsu)*/ ``` ::: ## [P13275 \[NOI2025\] 集合](https://www.luogu.com.cn/problem/P13275)