1. 程式人生 > >luoguP3370 【模板】字符串哈希 [hash]

luoguP3370 【模板】字符串哈希 [hash]

ons .cn 我想 max pac src 友情 mod 哈希

題目描述

如題,給定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人數的話),我想你一定會明白字符串哈希的正確姿勢的^_^


way1:map水過

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<map>
 5 #include<algorithm>
 6 #include<string>
 7 using
namespace std; 8 9 map<string,bool> ma; 10 string str; 11 int n,ans=0; 12 13 int main(){ 14 scanf("%d",&n); 15 for(int i=1;i<=n;i++){ 16 cin>>str; 17 if(!ma[str]){ 18 ma[str]=1; 19 ans++; 20 } 21 } 22 printf("%d\n",ans); 23 return 0; 24 }


map的效率大概是這樣的

技術分享

way2:建個鏈表hash

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<string>
 5 using namespace std;
 6 
 7 typedef long long ll;
 8 
 9 const int mod=10019,maxn=10005;
10 
11 int head[mod],len,nxt[maxn],cnt=0,n,ans=0;
12 ll p; 
13 string st[maxn];
14 string str;
15 
16 int gethash(){
17     len=str.length();  p=0;
18     for(int i=0;i<len;i++)
19         p=(p+(p+str[i]+131)*(str[i]+11)*str[i]*13)%mod;
20 }
21 
22 bool inc(){
23     for(int i=head[p];i;i=nxt[i]){
24         if(st[i]==str)  return 0;
25     }
26     st[++cnt]=str;
27     nxt[cnt]=head[p];
28     head[p]=cnt;
29     return 1;
30 }
31 
32 int main(){
33     scanf("%d",&n);
34     for(int i=0;i<n;i++){
35         cin>>str;
36         gethash();
37         ans+=inc();
38     }
39     printf("%d\n",ans);
40     return 0;
41 }

自建鏈表hash的效率大概是這樣的

技術分享

真是讓人困擾啊。。

luoguP3370 【模板】字符串哈希 [hash]