您的位置:首页 > 其它

poj 1200 (字符串hash)

2014-05-28 17:13 387 查看
题意:求一个字串中长度为n的不同子串的个数,原串中有nc个不同的字符。

解法:每个字符离散化成从0~nc-1,一个串就可以就有唯一的一个字串(就是把字母用数字代替),同样转换为十进制的话也是唯一的大小,判断有没有,如果已经不存在,标记,答 案++;

备注:北京邀请赛之前说好我做字符串的题,结果我也就是学了学KMP和后缀数组(学的还不怎么样),结果比赛的时候最后一个题(F题)一点没有思路,最近看到别人题解用hash来写,决定忍痛来学学hash,但是没有搜索到什么好的论文以及总结来供学习,基本上都是比较各种hash函数>_>,没办法只能靠刷题这样纸了...

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <deque>

#define maxn 16000000
#define ull unsigned long long
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))

const ull inf = 1LL << 61;

using namespace std;

bool cmp(int a,int b){
return a>b;
}
char str[maxn];
bool hash[maxn]={false};
int asi[256];
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int n,nc,ans=0;
cin>>n>>nc;
cle(asi);
scanf("%s",&str);
int len=strlen(str);
int i,j,k;
rep(i,len)asi[str[i]]=1;
int ip=0;
rep(i,256)if(asi[i])asi[i]=ip++;
rep(i,len-n+1){
int key=0;
rep(j,n){
key=key*nc+asi[str[i+j]];//转换成NC进制的数
}
if(hash[key]==0){
hash[key]=1,ans++;
}
}
cout<<ans<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: