Codeforces Round #124 (Div. 1) D. The Next Good String

4 篇文章 0 订阅
3 篇文章 0 订阅
#include<bits/stdc++.h>
#define N 400100
using namespace std;
typedef unsigned long long ULL;
const ULL MOD=29;
ULL cf[N],a[N];
int n,m;
char s[N];
inline void ex(){
	puts("Impossible");
	exit(0);
}
ULL h[N];
void dfs(int p,int f,ULL h1,ULL h2){
	if(p==n+1){
		for(int i=1;i<=n;i++) printf("%c",a[i]+'a'-1);
		puts("");
		exit(0);
	}
	if(f==0) a[p]=1;
	else a[p]=s[p]-'a'+1;
	ULL nh1,nh2;
	while(a[p]<=26){
		if(p>m) nh1=(h1-a[p-m]*cf[m-1])*MOD+a[p];
		else nh1=h1*MOD+a[p];
		nh2=h2+cf[p-1]*a[p];
		h[p]=nh2;
		if((p<m||nh1*cf[p-m]!=h[p]-h[p-m])&&(p<m+1||(a[p-m]*cf[m-1]*MOD+nh1)*cf[p-m-1]!=h[p]-h[p-m-1])) dfs(p+1,a[p]+'a'-1==s[p]&&f,nh1,nh2);
		a[p]++;
	}
}
int main(){
	scanf("%d%s",&m,s+1);
	n=strlen(s+1);
	s[n]++;
	for(int i=n;i;i--){
		if(s[i]>'z') s[i]='a',s[i-1]++;
		else break;
	}
	if(s[0]) ex();
	cf[0]=1;
	for(int i=1;i<=n;i++) cf[i]=cf[i-1]*MOD;
	dfs(1,1,0,0);
	ex();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值