CF 1968 G1.Division + LCP (easy version) (*1900) 二分+哈希

CF 1968 G1.Division + LCP (easy version) (*1900) 二分+哈希

题目链接

题意

给你一个字符串 \(s\) , 请你把字符串分割成 \(k\) 份。使得这些字符串的最长公共前缀的长度最大。

思路

最长公共前缀的长度具有单调性,因此可以进行二分。考虑如何check。我们可以贪心的去找出含有公共前缀的一段分成一组,然后比较分出的组数是否大于等于 \(k\) 即可。至于如何找出公共前缀可以用字符串哈希解决。

注意哈希数组开两倍空间,防止RE。

代码

#include<bits/stdc++.h>

using namespace std;

#define ff first
#define ss second
#define pb push_back
#define all(u) u.begin(), u.end()
#define endl '\n'
#define debug(x) cout<<#x<<":"<<x<<endl;

typedef pair<int, int> PII;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 1e5 + 10, M = 105;
const int mod = 1e9 + 7, mod1 = 1e9+9;
const int P1=131,P2=13331;
const int cases = 1;

void Showball(){
   int n,k;
   cin>>n>>k>>k;
   string s;
   cin>>s;
   s="?"+s; 
   vector<LL> p1(2*n+1),p2(2*n+1),h1(2*n+1),h2(2*n+1);
   p1[0]=p2[0]=1;
   for(int i=1;i<=n;i++){
      p1[i]=(p1[i-1]*P1)%mod;
      p2[i]=(p2[i-1]*P2)%mod1;
      h1[i]=((h1[i-1]*P1)%mod+s[i]-'0'+1)%mod;
      h2[i]=((h2[i-1]*P2)%mod1+s[i]-'0'+1)%mod1;
   }
   auto get1=[&](int l,int r){return (h1[r]-(h1[l-1]*p1[r-l+1])%mod+mod)%mod;};
   auto get2=[&](int l,int r){return (h2[r]-(h2[l-1]*p2[r-l+1])%mod1+mod1)%mod1;};

   auto check=[&](int mid){
      if(!mid) return true;
      int cnt=1;
      int hash1=get1(1,mid);
      int hash2=get2(1,mid);
      int i=mid+1;
      while(i<=n){
         if(get1(i,i+mid-1)==hash1&&get2(i,i+mid-1)==hash2) cnt++,i+=mid;
         else i++;
      }
      return cnt>=k;
   };

   int l=0,r=n;
   while(l<r){
      int mid=(l+r+1)>>1;
      if(check(mid)) l=mid;
      else r=mid-1;
   }
   cout<<l<<endl;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T=1;
    if(cases) cin>>T;
    while(T--)
    Showball();
    return 0;
}
posted @ 2024-06-23 02:32  Showball  阅读(1)  评论(0编辑  收藏  举报