Hash求LCP最长公共前缀

#include<cstdio>
#include<algorithm>
using namespace std;
typedef unsigned long long ULL;
const int maxl=40000,Base=233333333; //Base乱取(反正看RP)
int m,len,where,id[maxl+5];
char s[maxl+5];
ULL H[maxl+5],pw[maxl+5],ha[maxl+5]; //存在unsigned long long里,自然溢出
bool Eoln(char ch) {return ch==10||ch==13||ch==EOF;}
int readi(int &x){ //int读入优化
    int tot=0,f=1;char ch=getchar(),lst=' ';
    while ('9'<ch||ch<'0') {if (ch==EOF) return EOF;lst=ch;ch=getchar();}
    if (lst=='-') f=-f;
    while ('0'<=ch&&ch<='9') tot=tot*10+ch-48,ch=getchar();
    x=tot*f;
    return Eoln(ch);
}
int reads(char *s){ //char[]读入优化
    int len=0;char ch=getchar();if (ch==EOF) return EOF;
    s[++len]=ch;while (!Eoln(s[len])) s[++len]=getchar();s[len--]=0;
    return len;
}
ULL Hash(int x,int L) {return H[x]-H[x+L]*pw[L];} //计算Hash值
bool my_comp(const int &a,const int &b) {return ha[a]<ha[b]||ha[a]==ha[b]&&a<b;}
bool check(int L){
    for (int i=1;i<=len-L+1;i++) id[i]=i,ha[i]=Hash(i,L);
    sort(id+1,id+1+len-L+1,my_comp); //排序
    int i=1,j,tot;where=-1;
    while (i<=len-L+1){ //去重扫个数
        j=i;tot=0;
        while (j<=len-L+1&&ha[id[i]]==ha[id[j]]){
            tot++;if (tot>=m) where=max(where,id[j]-1);
            //如果上面没有判ha[a]==ha[b]&&a<b就会错误,因为只有tot>=m才会开始扫max
            j++;
        }
        i=j;
    }
    return where!=-1; //扫到答案
}
int main(){
    for (readi(m);m;readi(m)){
        len=reads(s);
        H[len+1]=0;for (int i=len;i>=1;i--) H[i]=H[i+1]*Base+s[i]; //预处理H[i]
        pw[0]=1;for (int i=1;i<=len;i++) pw[i]=pw[i-1]*Base; //预处理Base^L
        int L=1,R=len;
        while (L<=R){
            int mid=L+(R-L>>1);
            if (check(mid)) L=mid+1; else R=mid-1;
        }
        if (R==0) printf("none\n"); else check(R),printf("%d %d\n",R,where);
    }
    return 0;
}

【Hash求LCP最长公共前缀】
HDU4080题意:
给出一个m,然后给出一个字符串,输出在这个字符串里出现>=m次的子串的最大长度和最后出现的位置,如果没有,输出none。
Sample Input
3
baaaababababbababbab
11
baaaababababbababbab
3
cccccc
0
Sample Output
5 12
none
4 2

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值