hash 哈希

 

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 #define ull unsigned long long
 5 const int maxn=1e6+5;
 6 const int base=163;
 7 
 8 char s1[10005],s2[maxn];
 9 ull p[maxn],Hash[maxn];
10 
11 void init( char *c)
12 {
13     p[0]=1;
14     Hash[0]=0;
15     int k= strlen(c+1);
16     for(int i=1;i<=k;i++)
17         p[i]=p[i-1]*base;
18     for(int i=1;i<=k;i++)
19         Hash[i]=Hash[i-1]*base + (c[i]-'A'+1);
20 }
21 ull get(int l,int r)
22 {
23     return Hash[r]-Hash[l-1]*p[r-l+1];
24 }
25 
26 int main()
27 {
28     ios::sync_with_stdio(false);
29     int T;
30     cin>>T;
31     while(T--)
32     {
33         cin>>s1;
34         cin>>s2+1;
35         init(s2);
36         int len1=strlen(s1);
37         int len2=strlen(s2+1);
38 
39         int cnt=0;
40         ull pp=0;
41         for(int i=0;i<len1;i++)
42             pp=pp*base + (s1[i]-'A'+1);
43         for(int i=1; i+len1-1 <=len2;i++)
44         {
45             ull hs=get(i,i+len1-1);
46             if(hs==pp)
47                 cnt++;
48         }
49         cout<<cnt<<endl;
50     }
51 }

 

转载于:https://www.cnblogs.com/thunder-110/p/9322140.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值