2021威海D Period(哈希表)

感觉这题最大的困难在于理解period这个单词是什么意思。。。。
原文是
A integer number T is a period of a string s if and only if 1≤T<|s| and s[i]=s[i−T] for every i∈(T,|s|].
翻译过来就是找到一个最大的K,使得[1,k]与[n-k,n]这两段字符串相同
对于匹配相同字符串很容易想到用哈希表+前缀和实现
而题目中将一个字符改成’#‘说白了就是最长只能找到’#'前面这个位置(因为其他字符都是小写字母,不可能匹配到#)

#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int mod = 998244353;
const int N = 1e6 + 10;;
int a[N];
int s[N];
string ch;
int ok[N];

int get(int l, int r) {
    
    
	return a[r] - a[l - 1] * s[r - l + 1];
}

void solve() {
    
    
	cin >> ch;
	int n = ch.size();
	ch = " " + ch;
	s[0] = 1;
	for (int i = 1; i <= n; i++) {
    
    
		a[i] = a[i - 1] * 131 + ch[i];
		s[i] = s[i - 1] * 131;
	}
	for (int i = 1; i <= n / 2; i++) {
    
    
		if (get(1, i) == get(n - i + 1, n) ) {
    
    
			ok[i] = ok[i - 1] + 1;
		} else {
    
    
			ok[i] = ok[i - 1];
		}
	}
	int m;
	cin >> m;
	while (m--) {
    
    
		int x;
		cin >> x;
		cout << ok[min(n - x, x - 1)] << endl;
	}



}

signed main() {
    
    
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	solve();

}

おすすめ

転載: blog.csdn.net/fdxgcw/article/details/121531951