## E - (∀x∀) 解説 by en_translator

The following fact is obvious but very important when solving this problem.

A palindrome of length \(N\) is uniquely determine by its first \(\lceil \frac{N}{2} \rceil\) characters.

We will now explain the solution by examples.

First, we consider \(S=\) `ABCDE`

.
Obviously, if the first three characters are lexicographically smaller than or equal to `ABB`

, then the \(5\)-character palindrome determined by them is lexicographically smaller than \(S\). Conversely, if the first three characters are lexicographically larger than or equal to `ABD`

, then the \(5\)-character palindrome determined by them is lexicographically larger than \(S\).

The “issue” is that, what if the first \(3\) characters of the palindrome is `ABC`

, that is, if it is `ABCBA`

? For this string, comparing the first \(3\) characters is not enough to determine if the palindrome is lexicographically smaller than \(S\), so we have to actually compare this string with \(S\). This time, this string is lexicographically smaller than or equal to \(S\), so it satisfies the condition. What we have to count is the number of palindromes whose the first \(3\) characters are `AAA`

, `AAB`

, …, `ABB`

, or `ABC`

. These can be counted in the same way as computing an integer of base \(26\) (since each string can be interpreted as an integer of base \(26\) by viewing `A`

\(=0,\) `B`

\(=1,\dots,\) and `Z`

\(=25\).

Next, let’s consider the case \(S=\) `DCBA`

.
This time, we can do almost the same discussion. The only “issue” is when the palindrome whose the first two characters are `DC`

, that is, `DCCD`

. This time, this string is lexicographically larger than \(S\), so it does not satisfy the condition.

In any case, the problem can be solved by determining the following two questions:

- How many palindromes are there that are lexicographically smaller than the “issue” palindrome (that is, the palindrome whose the first \(\lceil \frac{N}{2} \rceil\) characters are equal to that of \(S\))?
- Does the “issue” palindrome satisfy the condition?

Note that, depending on implementation, it may be easier to solve it in the following way:

- Count the number of palindromes that are lexicographically smaller than or equal to the “issue” palindrome
- Decrement the count by \(1\) if the “issue” palindrome does not satisfy the condition

In the sample code, this method is used.

Sample code (C++):

```
#include<bits/stdc++.h>
#define mod 998244353
using namespace std;
int main(){
int tc;
cin >> tc;
while(tc>0){
tc--;
int n;
string s;
cin >> n >> s;
long long cres=0;
string target=s;
int p=0,q=n-1;
while(p<q){
target[q]=target[p];
p++;q--;
}
int last=(n-1)/2;
for(int i=0;i<=last;i++){
cres*=26;cres%=mod;
cres+=(s[i]-'A');cres%=mod;
}
cres++;cres%=mod;
if(s<target){cres+=(mod-1);cres%=mod;}
cout << cres << '\n';
}
return 0;
}
```

投稿日時:

最終更新: