LA 4513 Stammering Aliens

题目连接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2514


本题练习基于哈希值的LCP(最长公共前缀)算法,为每个后缀计算一个哈希值,满足递推式:H[i] = H[i-1]x + s[i],其中,H[n] = 0

对于长度为L的字符串,定义它的Hash值为Hash[i,L] = H[i] - H[i+L] x ^ L,其中x值是任意的。H和Hash数组保存成unsigned long long

二分法枚举长度即可。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;

#define Maxn 40005
#define  LL unsigned long long

const int x = 123;
char str[Maxn];
LL H[Maxn],xp[Maxn];
LL hash[Maxn];
int rank[Maxn];

int n,m;
//起始位置最大值
int pos = 0;

bool cmp(int a,int b)
{
    return hash[a] < hash[b] || (hash[a] == hash[b] && a < b);
}
void init()
{
    n = strlen(str);
    H[n] = 0;
    for(int i=n-1; i>=0; i--) H[i] = H[i+1]*x + (str[i] - 'a');
    xp[0] = 1;
    for(int i=1; i<=n; i++) xp[i] = xp[i-1] * x;

}
bool possible(int L)
{
    pos = -1;
    for(int i=0; i<n-L+1; i++)
    {
        rank[i] = i;
        hash[i] = H[i] - H[i+L]*xp[L];
    }
    sort(rank,rank + n - L + 1,cmp);

    int c = 1;
    for(int i=0; i<n-L+1-1; i++)
    {
        if(hash[rank[i]] == hash[rank[i+1]]) c++;
        else
        {
            if(c>=m)
            {
                pos = max(pos,rank[i]);
            }
            c = 1;
        }
    }
    if(c>=m)
    {
        pos = max(pos,rank[n-L]);
    }
    if(pos == -1) return false;
    return true;
}
int binarySearch()
{

    int ans;
    if(!possible(1))
    {
        puts("none");
        return 0;
    }
    int l = 1,r = n;
    int mid;
    ans = l;
    //二分枚举长度
    while(l<r)
    {
        mid = (l + r + 1)>>1;
        if(possible(mid))
        {
            ans = mid;
            l = mid;
        }
        else r = mid-1;
    }
    //别忘了再进行一次
    possible(ans);
    printf("%d %d\n",ans,pos);
    return 0;
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    while(scanf(" %d",&m)!=EOF && m!=0)
    {
        scanf(" %s",str);
        init();
        binarySearch();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值