搜索+hash,
长度为L的回文串一定包含长度为L-2的回文串。
判断回文的时候只要判断d和d+1不是回文串就可以了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long int ull;
const int maxn=500100;
char s[maxn],r[maxn];
int n,d;
ull p[maxn],hash[maxn],rhash[maxn];
bool ok(int ed,int d)
{
ed++;
int st=ed-d+1;
if(st<0) return true;
if((rhash[ed]-rhash[st-1]*p[d])*p[st-1]!=hash[ed]-hash[st-1])
return true;
return false;
}
bool dfs(int x,int t)
{
if(x==n)
{
puts(r);
return true;
}
for(r[x]=(t?s[x]:'a');r[x]<='z';r[x]++)
{
hash[x+1]=hash[x]+r[x]*p[x];
rhash[x+1]=rhash[x]*175+r[x];
if(ok(x,d)&&ok(x,d+1)&&dfs(x+1,t&&(r[x]==s[x])))
return true;
}
return false;
}
int main()
{
scanf("%d %s",&d,s);
n=strlen(s);
int i=n-1;
for(;i>=0&&s[i]=='z';i--)
s[i]='a';
if(i<0)
{
puts("Impossible");
return 0;
}
s[i]++;p[0]=1;
for(int i=1;i<n+100;i++)
p[i]=p[i-1]*175;
if(dfs(0,1)==false)
puts("Impossible");
return 0;
}