某个子串的循环节

题意:

给出一个长度为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~~

 

总结:

1.hash要搞对姿势,unsigned自动溢出

2.如果字符串出现循环节,假设循环节长度为x,那么[L, R - x] == [L+x, R]

 

代码:

#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;
}

  

转载于:https://www.cnblogs.com/xgtao/p/5967330.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值