首页 > 代码库 > 某个子串的循环节

某个子串的循环节

题意:

给出一个长度为n(<=5e4)的字符串,有m(<=2e6)个询问,询问这个字符串[L,R]区间的最小循环节长度。

 

题解:

首先需要明确两个东西:

1.假如询问的区间长度为len,那么循环节的长度必定为len的因数,那么只需要枚举len的因数就好了,复杂度为根号n

2.现在只需要检查枚举的循环节的长度是否符合条件,如果字符串出现循环节,假设循环节长度为x,那么[L, R - x] == [L+x, R]

3.现在的问题就是怎么判断[L, R - x] == [L+x, R],hash一下就好了O(∩_∩)O~~

 

代码:

#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int N = 5e5+7;
char ch[N];
vector <int> fac[N];
unsigned int pow[N],H[N],L,R,len,n,q;

int readint(){
	int K = 0; char c = getchar();
	while (c < ‘0‘ || c > ‘9‘) c = getchar();
	while (c >= ‘0‘ && c <= ‘9‘) K = K * 10 + c - ‘0‘, c = getchar();
	return K;
}

int hash(int L,int R){
	return H[R] - H[L - 1] * pow[R - L + 1];
}

int check(int len){
	return (hash(L + len, R) == hash(L, R - len));
}

int main(){
	scanf("%d%s%d", &n, ch + 1, &q);
	pow[0] = 1;
	for (int i = 1; i <= n; ++i) {
		H[i] = H[i-1] * 159 + ch[i] - ‘a‘;
		pow[i] = pow[i-1] * 159;
		for (int j = i; j <= n; j += i)
			fac[j].push_back(i);
	}
	while (q--) {
		L = readint(), R = readint(), len = R - L + 1;
		for (int i = 0; i < fac[len].size(); ++i){
			if (check(fac[len][i])) {
				printf("%d\n", fac[len][i]);
				break;
			}
		}
	}
	return 0;
}

  

某个子串的循环节