题目链接:https://acm.njupt.edu.cn/problem/CF535D/editor
KMP详解:https://blog.csdn.net/f1033774377/article/details/82556438
https://www.cnblogs.com/zhangtianq/p/5839909.html
题目大意是:
给出字符串p,在输入的m个pos[i]位置处插入p串,从而拼成长度为n的s串
主要解法思路:
有两种情况,pos[i]串与pos[i+1]串有重叠和没有重叠。
没有重叠时:
直接在空出的地方可以填上26个字母。
有重叠时:
利用KMP中的next计算出p串中每个位置处最大前缀后缀子串,利用这个找出p串中的最小循环体,当pos[i+1]与pos[i]串之间重叠 长度=p串中循环体长度(mark[pos[i]+len-pos[i]]==1)时候,可以重叠;否则,无法拼成s串。
注意对特殊情况的处理:
1、m==0时
2、pos[1]与1之间的空白,pos[m]与n之间的空白部分
3、放止插入p串后长度超过n
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
#define ll long long
const int maxn =1e6+10;
const int mod=1e9+7;
char p[maxn];
int n,m;
int Next[maxn]; //KMP算法next数组
int pos[maxn];
int mark[maxn]; //标记小循环末位位置
ll qpow(ll a, ll n){
ll res = 1;
while(n){
if(n&1) res = res*a%mod;
a = a*a%mod;
n >>= 1;
}
return res;
}
void get_next()
{
int len=strlen(p+1);
for (int i=2;i<=len;i++){
int j=Next[i-1];
while ((p[j+1]!=p[i])&&(j>0))
j=Next[j];
if (p[j+1]==p[i])
Next[i]=j+1;
else
Next[i]=0;
}
for(int i=len;i>0;i=Next[i])
mark[i]=1;
/* int j = 0;
int len = strlen(p+1);
for(int i = 2; i <= len; i++){
while(j && p[j+1] != p[i]){
j = Next[j];
}
if(p[j+1] == p[i]) j++;
Next[i] = j;
}
for(int i = len; i; i = Next[i]){
mark[i] = 1;
}*/
}
int main()
{
cin>>n>>m;
scanf("%s",p+1);
get_next();
int len=strlen(p+1);
for(int i=1;i<=m;i++)
scanf("%d",&pos[i]);
//特判m==0情况
if(!m)
{
cout<<qpow(26,n)<<endl;
return 0;
}
for(int i=1;i<=m;i++)
{
if(pos[i]+len-1>n)
{
cout<<0<<endl;
return 0;
}
if(i==1)
continue;
int pre=pos[i-1];
int cur=pos[i];
//pre+len-1为pos[i-1]串的末位
if(pre+len>cur)
{
//pre+len-cur 表示cur串与pre串的重叠部分长度
//如果长度刚好等于一个小循环 即mark[pre+len-cur]时,两串可以重叠在一起
if(!mark[pre+len-cur])
{
cout<<0<<endl;
return 0;
}
}
}
//t对pos[1]和pos[m]特殊的处理很关键
int t=pos[1]-1;
for(int i=2;i<=m;i++)
{
if(pos[i]>pos[i-1]+len)
t+=pos[i]-pos[i-1]-len;
}
t+=n-pos[m]-len+1;
cout<<qpow(26,t)<<endl;
return 0;
}