poj1200Crazy Search(hash)

题目大意   将一个字符串分成长度为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
",ans);
    return 0;
}
心若向阳,无言悲伤
折花枝,恨花枝,准拟花开人共卮,开时人去时。 怕相思,已相思,轮到相思没处辞,眉间露一丝。
原文地址:https://www.cnblogs.com/L-Memory/p/6241078.html