Text Editor Gym - 101466E (hash+二分)

  题目意思是给你一个主串和一个子串,然后要求你在子串的所有前缀串里找到一个最长的串,满足在主串里至少出现了ti次。

做法就是求出a串和b串的hash值,然后二分b串的长度就行了。

#include<bits/stdc++.h>//二分+hash
using namespace std;
#define ull unsigned long long
const int maxn=1e5+10;
ull hasha[maxn],hashb[maxn],base=131,ipow[maxn];
char a[maxn],b[maxn];
int lena,lenb,ans=-1,ti;
bool check(int mid)
{
    int tmp=0;
    for(int i=1;i<=lena-mid+1;i++)
    {
        ull zchash=hasha[i+mid-1]-hasha[i-1]*ipow[mid];
        if(zchash==hashb[mid])
        {
            tmp++;
            if(tmp==ti)
                return true;

        }
    }
    return false;

}
int main()
{
    gets(a+1);
    gets(b+1);
    lena=strlen(a+1);
    lenb=strlen(b+1);
    scanf("%d",&ti);
    //cout<<a<<endl<<b<<endl<<ti<<endl;
    hasha[0]=hashb[0]=0;
    ipow[0]=1;
    for(int i=1;i<=maxn;i++)
        ipow[i]=ipow[i-1]*base;
    for(int i=1;i<=lena;i++)
        hasha[i]=hasha[i-1]*base+a[i];
    for(int i=1;i<=lenb;i++)
        hashb[i]=hashb[i-1]*base+b[i];
    int low=1,up=lenb,mid;
    while(low<=up)
    {
        mid=(low+up)/2;
        if(check(mid))
        {
            ans=mid;
            low=mid+1;
        }
        else
            up=mid-1;
    }
    if(ans==-1)
        cout<<"IMPOSSIBLE"<<endl;
    else
    {
        for(int i=1;i<=ans;i++)
            cout<<b[i];
        cout<<endl;
    }


    return 0;

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值