您的位置:首页 > 其它

HDU 4821 String (字符串hash,技巧暴力)

2016-10-24 19:18 411 查看
题目链接

题目:是说给出一个字符串有几个不同的长度是M*L的子串,他们是由m个不同的长度是l的子串构成。

字符串hash,把字符串转化为一个整数,同时对于字串可以O(1)计算出他的hash值,类似前缀和的性质,本题要保证相同的字串hash值是一样 的,所以hash函数 sum[i] = sum[i-1]*p+str[i];这样倒着来。

暴力的时候,枚举开头的L个位置,以他们为起点找,然后找够了m个后,整体向后平移,继续找。

//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
#include<set>
#include<map>
#include<string>
#include<cassert>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define fastIO ios::sync_with_stdio(false);cin.tie(0);
#define LL long long
#define pb push_back
#define gcd __gcd

#define For(i,j,k) for(int i=(j);i<=k;i++)
#define lowbit(i) (i&(-i))
#define _(x) printf("%d\n",x)

typedef vector<LL> vec;
typedef pair<int,int> PI;
const double EPS = 1e-8;
const int maxn = 1e5+10;
const int inf  = 1 << 28;

char str[maxn];
LL p = 43, N = 1000000007;
int M,L;
LL pp[maxn]; LL sum[maxn];
void getHash(){
sum[0]=(LL)str[0];
for(int i=1;str[i];i++){
sum[i]=((sum[i-1]*p+(LL)str[i]%N)+N)%N;
}
}
LL getHash(int l,int r){
if(!l)return sum[r];
return ((sum[r]-sum[l-1]*pp[r-l+1])%N+N)%N;
}
map<LL,int> mp;
int main(){
pp[0]=1LL;
for(int i=1;i<maxn;i++){
pp[i]=(p*pp[i-1]%N+N)%N;
}
while(~scanf("%d%d",&M,&L)){
scanf("%s",str);
getHash();
int len = strlen(str);
int ans = 0;
for(int i=0;i<L;i++){
mp.clear();
for(int j=0;j<M&&i+(j+1)*L-1<len;j++){
mp[getHash(i+j*L,i+(j+1)*L-1)]++;
}
if(mp.size()==M)ans++;
for(int j=M;i+(j+1)*L-1<len;j++){
LL t = getHash(i+(j-M)*L,i+(j+1-M)*L-1);
if(--mp[t] == 0)mp.erase(t);
mp[getHash(i+j*L,i+(j+1)*L-1)]++;
if(mp.size()==M)ans++;
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: