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

#include
#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'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;
}

좋은 웹페이지 즐겨찾기