bitset 优化 LCS 学习笔记
其实广为人知(?)
省流:
前言
LCS 是初学者最先学的 dp 之一,其
答案是有的,虽然不能从根本上改变下限,但是可以让它在常规数据下跑得飞快。
该方法的理论基础最早源于 1986 年的 Allison-Dix 算法,后经 2001 年的 CIPR 算法优化,形成了如今的形式。
约定
以下默认读者会
要求 LCS 的两序列
朴素 dp 的状态是一张二维数表,从上到下第
在下文的二维数表中,相邻定义为四相邻,即两个数
正文
::::info[AI/LLM 使用声明]{open} 本文为纯人工手写,没有使用任何 AI 工具撰写文字,但是部分信息参考了 AI 提供的资料。 ::::
我们先从 LCS 的 dp 表的性质开始说起:
- 表中相邻两数
dp_{i,j},dp_{i',j'} 满足|dp_{i,j}-dp_{i',j'}|\le 1 。 - 表中的同一行从左到右单调不减。
性质 1,2 的证明是平凡的,此处略去。
容易发现把 dp 表按行差分为
我们考虑 dp 表的一行
为了方便转移,我们先用
for(int i=0;i<n;i++)p[a[i+1]].set(i);
注意代码与文章描述在下标上可能略有出入。
我们考虑什么时候
X=M|p[b[i]];
但是为什么不全是呢?因为当前面的一些
(1) (0 0 ... 0) 1 (0 0 ...) 1 ... 1 (0 0 ... 0)
括号中的表示可能有,就是划分成若干段,每段包括一段连续
(0 0 ...) 1 (1 ...) 2 (2 ...) 3 ...
现在有一些位置
(1) (0 ... 0 1 0 ... 0 1 0 ...0) 1 ...
* ^ ^
此时只有 * 对应的 ^ 对应的
::::info[什么你说为什么只能选一个?]
原来段中末尾的
因此我们要做的是在这个集合中对每个段找到最左边的
我们考虑这个过程,发现这像极了二进制减法的借位,碰到第一个
0 ... 0 1 0 ... 0 1 1
我们将其视作一个二进制整数,左边低位右边高位,然后把它减去最低位——
1 ... 1 0 0 ... 0 1 1
发现第一个 & 上
dif=X-B;
M=X&(~dif);
那么如何得到
B=(M<<1).set(0);
有的读者可能要问了,最高位的
这样,我们就从
最后的答案就是 M.count()。
这样,我们就把原本
实现
由于减法的关系,不能直接使用 std::bitset,需要使用奇技淫巧(如把 std::bitset 强转为 unsigned long long* 手动模拟减法,不建议用,在某些环境下是 UB),或者直接自己手写 bitset,笔者选择第二种。
以下给出模版题洛谷 B2175 的代码:
::::success[Code]
#include<bits/stdc++.h>
using namespace std;
const int N=5e3+5;
using ull=unsigned long long;
struct Bitset{
static const unsigned W=64,siz=N/W+1;
ull a[siz];
Bitset(){memset(a,0,sizeof(a));}
Bitset& set(unsigned pos){
a[pos>>6]|=(1ull<<(pos&63));return *this;
}
friend Bitset operator|(const Bitset& x,const Bitset& y){
Bitset res;
for(int i=0;i<siz;i++)res.a[i]=x.a[i]|y.a[i];
return res;
}
friend Bitset operator&(const Bitset& x,const Bitset& y){
Bitset res;
for(int i=0;i<siz;i++)res.a[i]=x.a[i]&y.a[i];
return res;
}
Bitset operator<<(unsigned x){
Bitset res=*this;
for(int i=siz-1;i;i--)res.a[i]<<=x,res.a[i]|=res.a[i-1]>>(W-x);
res.a[0]<<=x;
return res;
}
Bitset operator~(){
Bitset res=*this;
for(int i=0;i<siz;i++)res.a[i]=~res.a[i];
return res;
}
friend Bitset operator-(const Bitset& x,const Bitset& y){
Bitset res;
int borrow=0;
for(int i=0;i<siz;i++){
ull now=x.a[i]-y.a[i]-borrow;
if(x.a[i]<y.a[i]+borrow)borrow=1;else borrow=0;
res.a[i]=now;
}
return res;
}
unsigned count(){
unsigned res=0;
for(int i=0;i<siz;i++)res+=__builtin_popcountll(a[i]);
return res;
}
};
Bitset M,X,dif,B;
Bitset p[2*N];
int n,m;
int a[N],b[N];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m;
vector<int> lsh;
for(int i=1;i<=n;i++)cin>>a[i],lsh.push_back(a[i]);
for(int i=1;i<=m;i++)cin>>b[i],lsh.push_back(b[i]);
sort(lsh.begin(),lsh.end());
lsh.resize(unique(lsh.begin(),lsh.end())-lsh.begin());
for(int i=1;i<=n;i++)
a[i]=lower_bound(lsh.begin(),lsh.end(),a[i])-lsh.begin();
for(int i=1;i<=m;i++)
b[i]=lower_bound(lsh.begin(),lsh.end(),b[i])-lsh.begin();
for(int i=0;i<n;i++)p[a[i+1]].set(i);
for(int i=1;i<=m;i++){
X=M|p[b[i]];
B=(M<<1).set(0);
dif=X-B;
M=X&(~dif);
}
cout<<M.count()<<endl;
return 0;
}
::::
Record
由于笔者的手写 bitset 并不优秀,并且
结语
不知道写啥好。