题意:给你一个主串和模式串,找出模式串最大的前缀,使得其在主串中的出现次数大于等于n。
思路:
首先会想到KMP。但是如果直接拿模式串一位一位匹配是O(n2)的时间复杂度,肯定过不了。
我们发现模式串长度越长,越不容易满足要求。所以这里有个单调性,可以来二分。我们二分答案可能的长度,然后用这么长的前缀丢进KMP里面,看看能否满足,如果发现可以,就把长度调大一点,反之调小一点。时间复杂度O(nlogn)。
最后注意KMP用来计数时,每次匹配完不能直接j=0, i -= p.size(),因为这样会使得指针回溯使得算法退化。我们匹配完一个直接j = nxt[j]就行了(还是尽量选择前面最大匹配完的一部分接着匹配)。
AC代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include <queue>
#include<sstream>
#include <stack>
#include <set>
#include <bitset>
#include<vector>
#define FAST ios::sync_with_stdio(false)
#define abs(a) ((a)>=0?(a):-(a))
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define rep(i,a,n) for(int i=a;i<=n;++i)
#define per(i,n,a) for(int i=n;i>=a;--i)
#define endl '\n'
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PII;
const int maxn = 1e5+200;
const int inf=0x3f3f3f3f;
const double eps = 1e-7;
const double pi=acos(-1.0);
const int mod = 1e9+7;
inline int lowbit(int x){return x&(-x);}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
void ex_gcd(ll a,ll b,ll &d,ll &x,ll &y){if(!b){d=a,x=1,y=0;}else{ex_gcd(b,a%b,d,y,x);y-=x*(a/b);}}//x=(x%(b/d)+(b/d))%(b/d);
inline ll qpow(ll a,ll b,ll MOD=mod){ll res=1;a%=MOD;while(b>0){if(b&1)res=res*a%MOD;a=a*a%MOD;b>>=1;}return res;}
inline ll inv(ll x,ll p){return qpow(x,p-2,p);}
inline ll Jos(ll n,ll k,ll s=1){ll res=0;rep(i,1,n+1) res=(res+k)%i;return (res+s)%n;}
inline ll read(){ ll f = 1; ll x = 0;char ch = getchar();while(ch>'9'||ch<'0') {if(ch=='-') f=-1; ch = getchar();}while(ch>='0'&&ch<='9') x = (x<<3) + (x<<1) + ch - '0', ch = getchar();return x*f; }
int dir[4][2] = { {1,0}, {-1,0},{0,1},{0,-1} };
int nxt[maxn];
void getnext(string p)
{
mem(nxt,0);
nxt[0] = -1; //第一位设为-1
int i = 0, j = -1; //i指针用来遍历数组, j相当于最大公共前后缀长度
while(i<(int)p.size())
{
if(j==-1||p[i]==p[j]) i++, j++, nxt[i] = j; //看看前后缀是否相等
else j = nxt[j]; // 不行的话往前回溯
}
}
int KMP(string t, string p)
{
int i = 0, j = 0;
getnext(p);
int cnt = 0;
while(i<t.size())
{
if(j==p.size())
{
cnt++;
j = nxt[j];
}
if(j==-1||t[i]==p[j]) i++, j++; //相等继续
else j = nxt[j]; // 失配后找到nxt[j]的位置继续匹配。
}
if(j==p.size()) cnt++;
return cnt;
}
int main()
{
string t, p;
int n;
getline(cin,t);
getline(cin,p);
cin>>n;
int L = 1 , R = p.size();
string res = "-1";
while(L<=R)
{
int mid = (L+R)>>1;
string tmp(p,0, mid);
if(KMP(t,tmp)>=n) res = tmp, L = mid + 1;
else R = mid - 1;
}
if(res=="-1") cout<<"IMPOSSIBLE"<<endl;
else cout<<res<<endl;
return 0;
}