Oulipo(poj 3461)

题意:求b这个字符串在a中出现的次数

这里不用KMP,用hash

#include<cstdio>
#include<iostream>
#include<cstring>
#define P 29
#define N 1000010
using namespace std;
char a[N],b[N];int n1,n2,p,S,hash[N];
void get_p(){
    p=1;
    for(int i=1;i<=n1;i++)
        p*=P;
}
void get_hash(){
    S=0;
    for(int i=1;i<=n1;i++)
        S=S*P+a[i]-'a'+1;
    hash[0]=0;
    for(int i=1;i<=n2;i++)
        hash[i]=hash[i-1]*P+b[i]-'a'+1;
}
int query(int x){
    return hash[x+n1-1]-hash[x-1]*p;
}
int main(){
    int T;scanf("%d",&T);
    while(T--){
        scanf("%s%s",a+1,b+1);
        n1=strlen(a+1);n2=strlen(b+1);
        get_p();get_hash();
        int ans=0;
        for(int i=1;i<=n2-n1+1;i++)
            if(query(i)==S)ans++;
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2016-11-17 21:51  karles~  阅读(170)  评论(0编辑  收藏  举报