P10634 BZOJ2372 music 题解
简要题意
给定两个序列 ,求 中有多少个子串离散化后和 离散化后相同。,序列取值 。
思路
串串匹配考虑 KMP,但是这个离散化太难看了,KMP 处理不了。
众所周知,KMP、manacher、最小表示法等数个字符串算法都可以被 Hash 完爆(最多再带个 )。于是我们考虑 Hash。
于是 Hash 如何做呢?
先把 离散化之后 Hash 掉,然后考虑如何计算 的子串离散化之后的 Hash 值。
我们发现 离散化之后的 Hash 值是这样的:(以下 都指离散化后的 )
它等价于:
序列取值范围又很小,这启示我们可以分每种数字计算 Hash。
具体地,在计算 的 Hash 值时,我们枚举这个取值范围,如果这个区间内有 ,则答案就加上将子串中数字 视为 其他数字视为 的序列的 Hash 值乘上它的排名。
对于每个字符,这种序列的 Hash 值可以分别预处理并用常规的方法查询。查询一个区间内是否有某个数字,可以对每个数字维护这种序列的前缀和。
时间复杂度 。
代码
#include <cstdio>
#if __linux__
#define ge getchar_unlocked
#define pu putchar_unlocked
#else
#define ge getchar
#define pu putchar
#endif
using namespace std;
typedef unsigned __int128 ull;
char ch;
template <typename T>
inline void read(T &x) {
x=0;bool sgn=0;
while ('0'>ch||ch>'9') ch=ge(), sgn |= (ch=='-');
while ('0'<=ch&&ch<='9') x=x*10+ch-'0', ch=ge();
if (sgn) x=-x;
}
template <typename T>
inline void write(T x) {
if (x<0) pu('-'), x=-x;
static int sta[110], top=0;
do sta[top++]=x%10, x/=10; while (x);
while (top) pu(sta[--top]+'0');
}
const int N = 1e5+3, S = 27;
const ull base = 47, mod = 1e18+19;
int n, m, s, a[N], b[N], sum[S][N], id[S], cnt, ans[N], tot;
bool t[S];
ull h[S][N], pb[N], h1;
inline ull has(int l, int r){
ull res = 0;
int cnt = 0; // 当前数字的排名
for (int i=1;i<=25;++i)
if (sum[i][r]-sum[i][l-1]) // 区间内有 i
res = (res + (mod-h[i][l-1]*pb[r-l+1]%mod+h[i][r])*(++cnt)%mod)%mod; // 统计进最终 Hash 值
return res;
}
int main() {
read(n), read(m), read(s);
pb[0] = 1;
for (int i=1;i<=n;++i) pb[i] = pb[i-1]*base%mod, read(a[i]);
for (int i=1;i<=m;++i)
read(b[i]), t[b[i]] = 1;
for (int i=1;i<=25;++i)
if (t[i]) id[i] = ++cnt;
for (int i=1;i<=m;++i)
h1 = (h1*base+id[b[i]])%mod; // 离散化 B 并算 Hash 值
for (int i=1;i<=25;++i){
for (int j=1;j<=n;++j) { // 预处理 A 每种数字的序列的“前缀和”和“Hash 值”
sum[i][j] = sum[i][j-1]+(a[j]==i);
h[i][j] = (h[i][j-1]*base+(a[j]==i))%mod;
}
}
for (int i=1, j=m;j<=n;++i, ++j)
if (has(i, j)==h1) // 匹配并统计答案。
ans[++tot] = i;
write(tot), pu(10);
for (int i=1;i<=tot;++i) write(ans[i]), pu(10);
return 0;
}