zoukankan      html  css  js  c++  java
  • 某个子串的循环节

    题意:

    给出一个长度为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
    ", fac[len][i]);
    				break;
    			}
    		}
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    多阶段构建Docker镜像
    Docker容器跨主机通信
    数说海南——简单分析海南各市县近六年人口吸引力情况
    数说海南——透过几组数据简单分析近十年海南人口情况
    Kubernetes1.7—DNS安装
    BP神经网络
    Centos7——NFS(Network File System)服务
    Kafka中时间轮分析与Java实现
    Centos安装完成后,ifconfig:command not found
    Oracle VM VirtualBox虚拟机安装Centos
  • 原文地址:https://www.cnblogs.com/xgtao/p/5967330.html
Copyright © 2011-2022 走看看