1001.迴圈位移
題意:
定義一個字串[A] 它代表著是一個迴圈位移的字串. 給你T組資料,字串A, B.問你在B字串中有多少子串是[A]
Code:
#include<bits/stdc++.h> using namespace std; typedef unsigned long long ull; const int N = 1048580 * 2; const int P = 131; ull p[N], h1[N], h2[N]; void solve() { string a, b; cin >> a >> b; int n = a.size(), m = b.size(); a = a + a; for (int i = 0; i < (n << 1); i++) { h1[i + 1] = h1[i] * P + a[i]; } for (int i = 0; i < m; i++) { h2[i + 1] = h2[i] * P + b[i]; } map <ull, int> mp; for (int i = 0; i < n; i++) { mp[h1[i + n] - h1[i] * p[n]]++; } int ans = 0; for (int i = 0; i <= m - n; i++) { ans += mp[h2[i + n] - h2[i] * p[n]]; } cout << ans << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); p[0] = 1; for (int i = 1; i < N; i++) { p[i] = p[i - 1] * P; } int _; cin >> _; while(_--) solve(); return 0; }