通过分析我们能发现, 如果 i 以前放完了, i 以后随便放的话必定有解。
所以我们只要找出第一个比原串大的地方就好啦, 用hash来判断是不是回文。
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 5e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} int d, n; char s[N]; LL hs1[N], hs2[N], Pow[N], fPow[N]; LL power(LL a, LL b) { LL ans = 1; while(b) { if(b & 1) ans = ans * a % mod; a = a * a % mod; b >>= 1; } return ans; } const int B = 23333; const int fB = power(B, mod - 2); LL getHash1(int L, int R) { return (hs1[R] - hs1[L - 1] * Pow[R - L + 1] % mod + mod) % mod; } LL getHash2(int L, int R) { return (hs2[R] - hs2[L - 1] + mod) % mod * fPow[L] % mod; } bool check(int L1, int R1, int L2, int R2) { if(L1 <= 0) return true; return getHash1(L1, R1) != getHash2(L2, R2); } int main() { for(int i = Pow[0] = 1; i < N; i++) Pow[i] = Pow[i - 1] * B % mod; for(int i = fPow[0] = 1; i < N; i++) fPow[i] = fPow[i - 1] * fB % mod; scanf("%d%s", &d, s + 1); n = strlen(s + 1); if(d == 1) return puts("Impossible"), 0; int leno, lene; if(d & 1) { lene = d / 2 + 1; leno = d / 2 + 1; } else { lene = d / 2; leno = d / 2 + 1; } int where = 0; for(int i = 1; i <= n; i++) { bool flag = false; for(int j = s[i] + 1; j <= 'z'; j++) { hs1[i] = (hs1[i - 1] * B % mod + j) % mod; hs2[i] = (hs2[i - 1] + Pow[i] * j % mod) % mod; if(check(i - 2 * lene + 1, i - lene, i - lene + 1, i) && check(i - 2 * leno + 2, i - leno + 1, i - leno + 1, i)) { flag = true; break; } } if(flag) where = i; hs1[i] = (hs1[i - 1] * B % mod + s[i]) % mod; hs2[i] = (hs2[i - 1] + Pow[i] * s[i] % mod) % mod; if(!check(i - 2 * lene + 1, i - lene, i - lene + 1, i) || !check(i - 2 * leno + 2, i - leno + 1, i - leno + 1, i)) { break; } } if(!where) puts("Impossible"); else { for(int i = 1; i <= n; i++) { if(i >= where) { int down = i == where ? s[i] + 1 : 'a'; for(int j = down; j <= 'z'; j++) { hs1[i] = (hs1[i - 1] * B % mod + j) % mod; hs2[i] = (hs2[i - 1] + Pow[i] * j % mod) % mod; if(check(i - 2 * lene + 1, i - lene, i - lene + 1, i) && check(i - 2 * leno + 2, i - leno + 1, i - leno + 1, i)) { s[i] = j; break; } } } hs1[i] = (hs1[i - 1] * B % mod + s[i]) % mod; hs2[i] = (hs2[i - 1] + Pow[i] * s[i] % mod) % mod; } puts(s + 1); } return 0; } /* */