hash 模板

首先,附上hash完整模板,分析见:http://www.cnblogs.com/wsdestdq/p/6831041.html

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 
 6 typedef long long LL;
 7 
 8 int n;
 9 const int D = 131;
10 const int MD = 1e9 + 7;
11 int f[10001],g[10001];
12 string s;
13 
14 int prehash(int x) {
15     f[0]=0;
16     for(int i=1; i<=x; i++) 
17     f[i] = (1LL*f[i-1]*D+s[i-1])%MD;
18     
19     g[0] = 1;
20     for(int i=1; i<=x; i++) 
21     g[i] = 1LL*g[i-1]*D%MD;
22 }
23 
24 int hash(int l,int r) {
25     int a=f[r];
26     int b=(1LL*f[l-1]*g[r-l+1])%MD;
27     return (a-b+MD)%MD;
28 }
29 
30 int main() {
31     cin>>s;
32     n=s.length();
33     prehash(n);
34     
35     while(!cin.eof()) {
36         int l,r;
37         cin>>l>>r;
38         cout<<hash(l,r);
39     }
40     return 0;
41 }

 

然后(=@__@=),偶做了一个练手题!!

 

洛谷 P3370 【模板】字符串哈希

题目描述

如题,给定N个字符串(第i个字符串长度为Mi,字符串内包含数字、大小写字母,大小写敏感),请求出N个字符串中共有多少个不同的字符串。

友情提醒:如果真的想好好练习哈希的话,请自觉,否则请右转PJ试炼场:)

输入输出格式

输入格式:

第一行包含一个整数N,为字符串的个数。

接下来N行每行包含一个字符串,为所提供的字符串。

输出格式:

输出包含一行,包含一个整数,为不同的字符串个数。

输入输出样例

输入样例#1:
5
abc
aaaa
abc
abcc
12345
输出样例#1:
4

说明

时空限制:1000ms,128M

数据规模:

对于30%的数据:N<=10,Mi≈6,Mmax<=15;

对于70%的数据:N<=1000,Mi≈100,Mmax<=150

对于100%的数据:N<=10000,Mi≈1000,Mmax<=1500

样例说明:

样例中第一个字符串(abc)和第三个字符串(abc)是一样的,所以所提供字符串的集合为{aaaa,abc,abcc,12345},故共计4个不同的字符串。

Tip: 感兴趣的话,你们可以先看一看以下三题:

BZOJ3097:http://www.lydsy.com/JudgeOnline/problem.php?id=3097

BZOJ3098:http://www.lydsy.com/JudgeOnline/problem.php?id=3098

BZOJ3099:http://www.lydsy.com/JudgeOnline/problem.php?id=3099

如果你仔细研究过了(或者至少仔细看过AC人数的话),我想你一定会明白字符串哈希的正确姿势的^_^

思路:

  hash模板题,运用了set不能存放两个相同的元素的性质,最后输出set的大小就是不同的子串个数

(⊙v⊙)嗯~ 代码:

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<set>
 4 using namespace std;
 5 
 6 set<int>S;
 7 const long long D = 131;
 8 const long long MD = 1e9+7;
 9 const long long N = 2000;
10 long long n,m;
11 string s;
12 int p[N],f[N];
13 
14 int prehash(long long m) {
15     f[0] = 0;
16     for(long long i=1; i<=m; i++) 
17     f[i] = (1LL*f[i-1]*D+s[i-1])%MD;
18     
19     p[0] = 1;
20     for(long long i=1; i<=m; i++)
21     p[i] = 1LL*p[i-1]+D%MD;
22 }
23 
24 int ehash(int l,int r) {
25     long long a=f[r];
26     long long b=(1LL*f[l-1]*p[r-l+1])%MD;
27     return (a-b+MD)%MD;
28 }
29 
30 int main() {
31     cin>>n;
32     
33     while(n--) {
34         cin>>s;
35         m=s.length();
36         prehash(m);
37         S.insert(ehash(1,m));
38     }
39     cout<<S.size();
40     return 0;
41 }

 

自己选的路,跪着也要走完!!!

转载于:https://www.cnblogs.com/wsdestdq/p/6832185.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值