HDU - 4821 String(哈希+滑动窗口)

传送门


一开始以为怎么写都会超时,因为要以每个点为起点向后查找 M L M*L 长度的字符串,以每个字符串为起点长度 L L 的子串的哈希可以预处理,但是如果向后滑动的话,所有长度为 L L 的哈希值都会改变,需要重新算吗?

答案是否定的,实际上我们只需考虑长度 [ 1 , L ] [1,L] 的字符作为起点,然后每次向后滑动 L L 的长度即可

#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define ins insert
#define Vector Point
#define lowbit(x) (x&(-x))
#define mkp(x,y) make_pair(x,y)
#define mem(a,x) memset(a,x,sizeof a);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<double,double> pdd;
const double eps=1e-8;
const double pi=acos(-1.0);
const int inf=0x3f3f3f3f;
const double dinf=1e300;
const ll INF=1e18;
const int Mod=1e9+7;
const int maxn=1e5+10;

const ull base=131;
ull bn[maxn],L[maxn],hashe[maxn];
unordered_map<ull,int> mp;
char s[maxn];
int m,l;

int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    //ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    hashe[0]=0,bn[0]=1;
    for(int i=1;i<maxn;i++) bn[i]=bn[i-1]*base;
    while(~scanf("%d%d",&m,&l)){
        scanf("%s",s+1);
        int n=strlen(s+1);
        if(m*l==1){  //特判长度为1
            printf("%d\n",n);
            continue;
        }
        for(int i=1;i<=n;i++) hashe[i]=hashe[i-1]*base+(ull)s[i];
        for(int i=1;i<=n-l+1;i++)  //预处理每个起点后长度为L的哈希值
            L[i]=hashe[i+l-1]-hashe[i-1]*bn[l];
        int ans=0;
        for(int k=1;k<=l && k+m*l<=n;k++){
            mp.clear();
            for(int i=k,j=1;j<=m;i+=l,j++){  //预处理开头的M*L
                mp[L[i]]++;
                //cout<<i<<" ";
            }
            //cout<<endl;
            if(mp.size()==m) ans++;
            for(int i=m*l+k;i<=n;i+=l){ 
                if(i>n-l+1) break;  //特判后面长度小于L的情况
                //cout<<i-m*l<<" "<<i<<endl;
                mp[L[i-m*l]]--,mp[L[i]]++;
                if(mp[L[i-m*l]]==0) mp.erase(L[i-m*l]);  //注意这里一定要删除
                if(mp.size()==m) ans++;
            }
            //cout<<"--------------"<<endl;
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44691917/article/details/107566595