相似的字串

題目:相似的字串

題解:這個答案滿足單調性,所以可以用二分寫。用Hash來判斷是否有相同的子串,對於其中可能有重疊的部分,用map將字串相同的進行比較。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int N = 2e5+10;
const ll inf = 1000000000000000000;
int base = 131;

ll Hash[N],po[N];
char s[N];
int n,k;

bool judge(int x){
    map<ll,P>vis;
    for(int i = x;i <= n;i++){
        ll t = Hash[i]-Hash[i-x]*po[x];//可以用來判斷一個字符串是否有相同的字串
        if(i-x >= vis[t].first){
            vis[t].first = i;
            vis[t].second++;
        }
        if(vis[t].second >= k) return true;
    }
    return false;
}
int main(){

    //freopen("in.txt","r",stdin);
    scanf("%d%d",&n,&k);
    scanf("%s",s+1);
    po[0] = 1ll;
    for(int i = 1;i <= n;i++){
        Hash[i] = Hash[i-1]*base+s[i]-'a';
        po[i] = po[i-1]*base;
    }
    int l = 1,r = n;
    int ans = 0;
    while(l <= r){
        int mid = (l+r)/2;
        if(judge(mid)){
            ans = mid;
            l = mid+1;
        }else {
            r = mid-1;
        }
    }
    cout<<ans<<endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章