题解:P17581 [JAG 2026 Summer Camp #3] Forbidden Word
横向出现就是原串中的普通出现,只是不能跨越行尾。先用 KMP 找到全部匹配起点,再从后向前计算
纵向匹配对应等差下标。若从下标
为了同时检查一批起点,对每个字符建立位集,第
代码用 unsigned long long 数组保存位集,一次处理
复杂度分析
记机器字长为
参考代码
#include <bits/stdc++.h>
using namespace std;
using ull = unsigned long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int cases;
cin >> cases;
while (cases--) {
int n, m;
string s, t;
cin >> n >> m >> s >> t;
if (m == 1) {
cout << string(n, s.find(t[0]) == string::npos ? '0' : '1') << '\n';
continue;
}
vector<int> pi(m), next(n + 1, n);
for (int i = 1, j = 0; i < m; ++i) {
while (j && t[i] != t[j]) j = pi[j - 1];
if (t[i] == t[j]) ++j;
pi[i] = j;
}
for (int i = 0, j = 0; i < n; ++i) {
while (j && s[i] != t[j]) j = pi[j - 1];
if (s[i] == t[j]) ++j;
if (j == m) next[i - m + 1] = i - m + 1, j = pi[j - 1];
}
for (int i = n - 1; i >= 0; --i) next[i] = min(next[i], next[i + 1]);
string ans(n, '0');
for (int d = m; d <= n; ++d) {
for (int l = 0; l < n; l += d) if (next[l] + m <= min(l + d, n)) {
ans[d - 1] = '1';
break;
}
}
int words = (n + 63) / 64;
vector<vector<ull>> pos(26, vector<ull>(words + 1));
for (int i = 0; i < n; ++i) pos[s[i] - 'a'][i / 64] |= 1ULL << (i % 64);
for (int d = 1; 1LL * (m - 1) * d < n; ++d) {
if (ans[d - 1] == '1') continue;
int count = n - (m - 1) * d;
for (int b = 0; b * 64 < count; ++b) {
ull cur = pos[t[0] - 'a'][b];
for (int j = 1; j < m && cur; ++j) {
int shift = j * d, at = b + shift / 64, rem = shift % 64;
ull v = pos[t[j] - 'a'][at] >> rem;
if (rem) v |= pos[t[j] - 'a'][at + 1] << (64 - rem);
cur &= v;
}
if (b * 64 + 64 > count) cur &= (1ULL << (count - b * 64)) - 1;
if (cur) {
ans[d - 1] = '1';
break;
}
}
}
cout << ans << '\n';
}
}