【BNUOJ 34990 】 Justice String 【基于Hash的LCP】

Given two strings A and B, your task is to find a substring of A called justice string, which has the same length as B, and only has at most two characters different from B.

Input
The first line of the input contains a single integer T, which is the number of test cases.
For each test case, the first line is string A, and the second is string B.
Both string A and B contain lowercase English letters from a to z only. And the length of these two strings is between 1 and 100000, inclusive.

Output
For each case, first output the case number as “Case #x: “, and x is the case number. Then output a number indicating the start position of substring C in A, position is counted from 0. If there is no such substring C, output -1.
And if there are multiple solutions, output the smallest one.

Sample Input
3
aaabcd
abee
aaaaaa
aaaaa
aaaaaa
aabbb
Sample Output
Case #1: 2
Case #2: 0
Case #3: -1

分析: 枚举A的起点,然后求子串s和B的LCP,看能否跳过最多2个字符,匹配成功。
代码

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define ULL unsigned long long

const int  N = (int)2e5+11;
const int M = (int)1e6+11;
const int mod = (int)1e9+7;
const int seed = (int) 233;
const int inf = 0x3f3f3f3f;

ULL H[N*2],X[N*2];
void init(char *s){
    int len=strlen(s);
    H[len]=0;
    for(int i=len-1;i>=0;i--){
        H[i]=H[i+1]*seed+s[i]-'a';
    }
    X[0]=1;
    for(int i=1;i<=len;i++){
        X[i]=X[i-1]*seed;
    }
}

char A[N*2],B[N];
inline ULL getHash(int a,int mid){
    return H[a]-H[a+mid]*X[mid];
}

int lena,lenb;int L ;
int LCP(int a,int b){  // log的时间求出 LCP 
    int le=1,ri=L-b;
    int ans=0;
    while(le<=ri){
        int mid=(le+ri)>>1;
        if(getHash(a,mid) == getHash(b,mid)) {
            ans=max(ans,mid);
            le=mid+1;
        }else ri=mid-1;
    }
    return ans;
}

int main(){
    int t; scanf("%d",&t); int cas=1;
    while(t--){
        scanf("%s%s",&A,&B);
        lena=strlen(A); lenb=strlen(B);  L=lena+lenb;
        strcat(A,B);
        init(A);
        int ans=-1;
        for(int i=0;i<lena-lenb+1;i++){
             int l1=LCP(i,lena);
             if(l1==lenb)  {ans=i; break;}
             l1++;
             int l2=LCP(i+l1,lena+l1);
             if(l2+l1==lenb) {ans=i; break;}
             l2++;
             int l3=LCP(i+l1+l2,lena+l1+l2);
             if(l1+l2+l3==lenb) {ans=i; break;}
        }

        printf("Case #%d: %d\n",cas++,ans);
    }
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值