[jzoj5462]【NOIP2017提高A组冲刺11.8】好文章

标签:哈希

传送门

Solution

题目实际要求我们求出重复的子串数

容易想到的 可以求出每个子串的 hash 值 然后排序 最后扫一遍

那么这里也浅谈一下 hash 算法

My Style

我一般会设两个质数 称较小的为 p 较大的为 P

比较基本的

HStr=stripi(modP)

为了防止被卡时间 减少代码复杂度

我们同时用多个 hash

一个或两个作为键值 剩下的用于判断是否完全相同


这道题的特点在于 所有字符串都是一个串的子串

所以令设 hi 表示 str[1,i] 的 hash 值

用上述的方式计算即可简便地判断

具体见标程的 hash 函数

Code

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define fo(i,x,y) for (int i=(x);i<=(y);++i)
#define fd(i,x,y) for (int i=(x);i>=(y);--i)
#define oo 2139062143
using namespace std;
const int N=200200,PRI1=39916801/*11!+1*/,PRI2=9191891;
int n,m;
char st[N];
struct node{
    int x,y;
}c[N];
int h1[N],h2[N];
int p1[N],p2[N];
int hash1(int sta)
{
    int l=sta,r=sta+m-1;
    return(1ll*(h1[r]-h1[l-1]+PRI1)%PRI1*p1[n-r]%PRI1);
}
int hash2(int sta)
{
    int l=sta,r=sta+m-1;
    return(1ll*(h2[r]-h2[l-1]+PRI2)%PRI2*p2[n-r]%PRI2);
}
bool cmp(node a,node b)
{
    return(a.x<b.x||(a.x==b.x&&a.y<b.y));
}
int main()
{
    // freopen("article.in","r",stdin);
    // freopen("article.out","w",stdout);
    scanf("%d%d\n%s",&n,&m,st+1);
    p1[0]=p2[0]=1,p1[1]=9209,p2[1]=3881;
    fo(i,2,n+100) p1[i]=(1ll*p1[i-1]*p1[1])%PRI1,p2[i]=(1ll*p2[i-1]*p2[1])%PRI2; 
    fo(i,1,n) 
    {
        int now=st[i]-'a'+1;
        h1[i]=(h1[i-1]+1ll*now*p1[i])%PRI1,h2[i]=(h2[i-1]+1ll*now*p2[i])%PRI2;

    }int tot=n-m+1;
    int tmp1=hash1(1);
    int tmp2=hash1(2); 
    fo(i,1,tot)
        c[i].x=hash1(i),c[i].y=hash2(i);    
    sort(c+1,c+1+tot,cmp);
    int ans=tot;
    fo(i,2,tot)
        if(c[i].x==c[i-1].x&&c[i].y==c[i-1].y) 
            --ans;
    printf("%d\n",ans);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值