首页 > 其他 > 详细

poj1200Crazy Search(hash)

时间:2017-01-01 16:22:03      阅读:188      评论:0      收藏:0      [点我收藏+]

题目大意   将一个字符串分成长度为N的字串。且不同的字符不会超过NC个。问总共有多少个不同的子串。

 

 

技术分享
/*
字符串hash O(n)枚举起点
然后O(1)查询子串hash值
然后O(n)找不一样的个数
复杂度是线性的 
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define P 29
#define maxn 1000010

using namespace std;
int n,c,len,p[maxn],ha[maxn],tot,hash[maxn],ans;
char s[maxn];

void Get_p()
{
    p[0]=1;
    for(int i=1;i<=n;i++)
        p[i]=p[i-1]*P;
}

void Get_ha()
{
    len=strlen(s+1);
    for(int i=1;i<=len;i++)
      ha[i]=ha[i-1]*P+s[i]-a;
}

int Query(int l,int r)
{
    return ha[r]-ha[l-1]*p[r-l+1];
}

void Solve()
{
    for(int l=1;l+n-1<=len;l++)
    {
        int r=l+n-1;
        hash[++tot]=Query(l,r);
    }
    sort(hash+1,hash+1+tot);
    for(int i=1;i<=tot;i++)
      if(hash[i]!=hash[i-1])ans++;
}

int main()
{
    scanf("%d%d%s",&n,&c,s+1);
    Get_p();Get_ha();Solve();
    printf("%d\n",ans);
    return 0;
}
心若向阳,无言悲伤

 

poj1200Crazy Search(hash)

原文:http://www.cnblogs.com/L-Memory/p/6241078.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!