HDU 4821 String 字符串哈希
来源:互联网 发布:js缩略图点击放大 编辑:程序博客网 时间:2024/04/29 06:32
链接:http://acm.hdu.edu.cn/showproblem.php?pid=4821
题意:给出M和L,和一个字符串S。要求找出S的子串中长度为L*M,并且可以分成M段,每段长L,并且M段都不相同的子串个数。
思路:一道字符串哈希题。哈希的方法是BKDRHash,哈希中进制是31,131等素数,(我还以为这是我自己想出来的哈希方法,原来不是,而且进制也不是我选择的26,而是31这样的素数。)
从len-1开始哈希,Hash[i]=Hash[i+1]*SEED+(ss[i]-'a'+1)。O(n)内计算出整个长串的哈希值。在其中长为L的子串的哈希值是Hash[i]-Hash[j+L]*K[L]。
由于M*L<=10^5,所以在检索过程中复杂度最多是O(M*L)。比赛中想到了一种O(M*L)的写法,不过姿势不够优美,挂掉了。优美的姿势是用unsigned long long 的map映射每段长度L的哈希值,用P.size()记录共出现了多少种不同哈希值,如果P.size()=M,则出现了一种符合题意的子串。
在哈希过程中unsighed long long 范围是0~18446744073709551615,并且会自动取模,所以在哈希过程中不需要%MOD这样的出现了。
资料:https://www.byvoid.com/blog/string-hash-compare/
代码:
#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<map>#include<cstdlib>#include<queue>#include<stack>#include<vector>#include<ctype.h>#include<algorithm>#include<string>#define PI acos(-1.0)#define maxn 10005#define INF 0x7fffffff#define SEED 31typedef long long LL;typedef unsigned long long ULL;using namespace std;map < ULL , int > P;ULL Hash[100005];ULL K[100005];int main(){ int M,L; char ss[100005]; while(scanf("%d%d",&M,&L)!=EOF) { ULL tt=1; scanf("%s",ss); int len=strlen(ss); ULL res=0; Hash[len]=0; K[0]=1; for(int i=1; i<=L; i++) K[i]=K[i-1]*SEED; for(int i=len-1; i>=0; i--) { Hash[i]=Hash[i+1]*SEED+(ss[i]-'a'+1); } int t=0,aa=0; for(int i=0; i<L&&i+M*L<len; i++) { P.clear(); for(int j=i; j<M*L+i; j+=L) { P[Hash[j]-Hash[j+L]*K[L]]++; } if(P.size()==M) aa++; for(int j=M*L+i; j<=len-L; j+=L) { int head= j-M*L; P[Hash[head]-Hash[head+L]*K[L]]--; if(P[Hash[head]-Hash[head+L]*K[L]]==0) P.erase(Hash[head]-Hash[head+L]*K[L]); P[Hash[j]-Hash[j+L]*K[L]]++; if(P.size()==M) aa++; } } printf("%d\n",aa); } return 0;}
5 1
- HDU 4821 String 字符串哈希
- HDU 4821 String 字符串哈希
- HDU 4821 String(字符串哈希)
- 2013ICPC 长春I HDU 4821 String 字符串哈希
- [hdu 4821]String 字符串hash
- HDU 4821 String 字符串hash
- [字符串hash] hdu 4821 String
- HDU 4821 String 字符串HASH
- HDU 4821 String 字符串HASH
- hdu 4821 String 字符串hash
- hdu 4821 String(枚举 + 字符串hash)
- HDU 4821 String(字符串hash)
- HDU 4821 String 字符串hash(水
- hdu 4821 String(字符串hash+map)
- [HDU 4821]String[字符串hash][存疑]
- hdu 4821String(字符串hash)
- HDU 4821String(字符串hash)
- HDU 4821 字符串哈希
- 工作二三事
- /usr/bin/ld: errno: TLS definition in /lib/libc.so.6 section
- hdu 2001两点距离20140721
- Linux命令学习记录
- [Python]利用type()动态创建类
- HDU 4821 String 字符串哈希
- Eclipse下使用Ant多渠道批量打包
- 基于glib的单线程多事件源处理
- hiho一下 第三周 "KMP"算法
- ADF 生产环境中SavePoint的创建与清除
- OCP 1Z0 053 183
- [leetcode] Valid Parentheses
- 有关C/C++的一些基础知识
- 湖大训练赛2 Modified LCS