字符串Hash || BZOJ 3555: [Ctsc2014]企鹅QQ || P4503 [CTSC2014]企鹅QQ

题面:[CTSC2014]企鹅QQ

题解:无

代码:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<cstdlib>
 5 #include<cmath>
 6 #include<map>
 7 #include<algorithm>
 8 #define ll long long
 9 #define max(a,b) ((a)>(b)?(a):(b))
10 #define min(a,b) ((a)<(b)?(a):(b))
11 #define fo(i,a,b) for(int i=a;i<=b;i++)
12 #define fd(i,a,b) for(int i=a;i>=b;i--)
13 typedef unsigned long long ull;
14 using namespace std;
15 const int maxn=30000+500,maxl=250;
16 int N,L,S,lA,lB,base=13331;
17 ull power[maxl],mo=1e9+7,sum[maxn][maxl],h[maxn],H[maxn];
18 ll A,B,ans=0,temp;
19 char str[maxn][maxl];
20 ull hash(int i,int x,int y){
21     return (sum[i][y]-sum[i][x-1]*power[y-x+1]);
22 }
23 int main(){
24     scanf("%d%d%d",&N,&L,&S);    
25     power[0]=1;
26     for(int i=1;i<=205;i++){
27         power[i]=power[i-1]*base;
28     }
29     
30     for(int i=1;i<=N;i++)scanf("%s",str[i]+1);
31     for(int i=1;i<=N;i++){
32         for(int j=1;j<=L;j++){
33             sum[i][j]=sum[i][j-1]*base+str[i][j];
34         }
35     }
36     for(int i=1;i<=L;i++){
37         for(int j=1;j<=N;j++){
38             if(i==1){
39                 H[j]=hash(j,2,L);
40             }
41             else if(i==L){
42                 H[j]=hash(j,1,L-1);
43             }
44             else{
45                 A=hash(j,1,i-1);
46                 B=hash(j,i+1,L);
47                 H[j]=A*power[L-i]+B;
48             }
49         }
50         sort(H+1,H+N+1);
51         temp=1;
52         for(int j=2;j<=N;j++){
53             if(H[j]==H[j-1]){
54                 ans+=temp;
55                 temp++;
56             }
57             else temp=1;
58         }
59     }
60     printf("%lld",ans);
61     return 0;
62 }

Tips:

字符串hash拼接公式:

拼接串a和串b:hash[a]*(power[lenb])+hash[b]


By:AlenaNuna

原文地址:https://www.cnblogs.com/AlenaNuna/p/10776927.html