#P12550. [UOI 2025] Reversal ABC

[UOI 2025] Reversal ABC

题目描述

Given a string ss consisting of characters A\texttt{A}, B\texttt{B}, and C\texttt{C}.

In one operation, you are allowed to choose two adjacent elements of the string sisi+1s_is_{i+1} that are in the following order: AB\texttt{AB}, BC\texttt{BC}, or CA\texttt{CA}, and swap them.

Find the maximum number of consecutive operations that can be performed on the string ss.

In this problem, each test contains several sets of input data. You need to solve the problem independently for each such set.

输入格式

The first line contains one integer TT (1T105)(1\le T\le 10^5) --- the number of sets of input data. The description of the input data sets follows.

In the first line of each input data set, there is one integer nn (1n106)(1 \le n \le 10^6) --- the length of the string ss.

In the second line of each input data set, there is a string ss of length nn, consisting of characters A\texttt{A}, B\texttt{B}, and C\texttt{C}.

It is guaranteed that the sum of nn across all input data sets of a single test does not exceed 10610^6.

输出格式

For each set of input data, output on a separate line one integer --- the maximum number of consecutive operations that can be performed on the string ss.

2
5
ABCCA
19
CCAABBBABBAAABBCCAA
3
28

提示

In the first set of input data from the first example, no more than 33 consecutive operations can be performed on the string ABCCA\texttt{ABCCA}. One example of how 33 consecutive operations can be performed is $[\texttt{ABCCA} \rightarrow \texttt{BACCA}, \texttt{BACCA} \rightarrow \texttt{BACAC}, \texttt{BACAC} \rightarrow \texttt{BAACC}]$.

Scoring

Let KK be the sum of nn over all input data sets of one test.

  • (22 points): the answer is equal to 00 or 11;
  • (33 points): n3n \le 3;
  • (55 points): siCs_i \ne \texttt{C} for 1in1 \le i \le n;
  • (55 points): ss has the form $\texttt{AA}\ldots \texttt{AABB}\ldots \texttt{BBCC}\ldots \texttt{CC}$ (that is, $x \cdot \texttt{A} + y \cdot \texttt{B} + z \cdot \texttt{C}$ for certain positive xx, yy, zz);
  • (99 points): sisi+1CAs_is_{i+1} \ne \texttt{CA} for 1i<n1 \le i < n;
  • (1010 points): T=1T = 1, n12n \le 12;
  • (88 points): n12n \le 12;
  • (2828 points): K2000K \le 2000;
  • (3030 points): without additional constraints.