BJS and HT
[Link](C-BJS and HT_第五届石家庄铁道大学程序设计竞赛 (nowcoder.com))
题意
给你多组情况,每组两个字符串A,B和一个整数k,如果满足B的前k个字符组成的子串在A中出现过,且将它挪到A的最前面,剩下的顺次拼接组成的新串是否和B一样。
题解
字符串哈希,把一个字符串映射成p进制的数就,原串靠左的是高位,靠右的是低位,然后利用一个前缀和的思想即可处理出来任意一段的和,例如求区间 [ l , r ] [l,r] [l,r],则只需要让 h r − h l − 1 × p r − l + 1 h_r-h_{l-1}\times p_{r - l + 1} hr−hl−1×pr−l+1即可,因为 h l − 1 h_{l-1} hl−1和 h r h_{r} hr中的那段是相差了 ( r − l + 1 ) (r-l + 1) (r−l+1)位的。把字符串哈希后暴力枚举当前长度以及拼接后是否满足即可。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#include <deque>
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 5e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7, P = 131;
const double eps = 1e-8, pi = acos(-1), inf = 1e20;
#define tpyeinput int
inline char nc() {static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
inline void read(tpyeinput &sum) {char ch=nc();sum=0;while(!(ch>='0'&&ch<='9')) ch=nc();while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();}
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int res;
ULL hb[N], hg[N], p[N];
char strb[N], strg[N];
ULL getb(int l, int r) { // 左高右低,平移即可
return hb[r] - hb[l - 1] * p[r - l + 1];
}
ULL getg(int l, int r) {
return hg[r] - hg[l - 1] * p[r - l + 1];
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int T; p[0] = 1;
cin >> T;
while (T -- ) {
cin >> strb + 1 >> strg + 1 >> k;
n = strlen(strb + 1);
if (n != strlen(strg + 1) || !k || k > n) continue ;
// cout << strb + 1 << endl;
for (int i = 1; i <= n; i ++ ) {
hb[i] = hb[i - 1] * P + strb[i];
hg[i] = hg[i - 1] * P + strg[i];
p[i] = p[i - 1] * P;
}
ULL tag = getg(1, k);
for (int i = 1; i <= n - k + 1; i ++ ) {
if (getb(i, i + k - 1) == tag) {
if (getb(1, i - 1) == getg(k + 1, k + i - 1) && getb(i + k, n) == getg(k + i, n)) {
res ++;
break;
}
}
}
}
cout << res << endl;
return 0;
}