#L10720. [GESP202406 五级] 小杨的幸运数字
[GESP202406 五级] 小杨的幸运数字
CF1987G2 Spinning Round (Hard Version)
题目描述
This is the hard version of the problem. The only difference between the two versions are the allowed characters in . You can make hacks only if both versions of the problem are solved.
You are given a permutation of length . You are also given a string of length , where each character is either L, R, or ?.
For each from to :
- Define as the largest index such that . If there is no such index, .
- Define as the smallest index such that . If there is no such index, .
Initially, you have an undirected graph with vertices (numbered from to ) and no edges. Then, for each from to , add one edge to the graph:
- If L, add the edge to the graph.
- If R, add the edge to the graph.
- If ?, either add the edge or the edge to the graph at your choice.
Find the maximum possible diameter over all connected graphs that you can form. Output if it is not possible to form any connected graphs.
Let denote the smallest number of edges on any path between and .
The diameter of the graph is defined as the maximum value of over all pairs of vertices and .
输入格式
Each test contains multiple test cases. The first line of input contains a single integer ( ) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer ( ) — the length of the permutation .
The second line of each test case contains integers ( ) — the elements of , which are guaranteed to form a permutation.
The third line of each test case contains a string of length . It is guaranteed that it consists only of the characters L, R, and ?.
It is guaranteed that the sum of over all test cases does not exceed .
输出格式
For each test case, output the maximum possible diameter over all connected graphs that you form, or if it is not possible to form any connected graphs.
输入输出样例 1
8
5
2 1 4 3 5
R?RL?
2
1 2
LR
3
3 1 2
L?R
7
5 3 1 6 4 2 7
?R?R?R?
5
5 2 1 3 4
?????
6
6 2 3 4 5 1
?LLRLL
8
1 7 5 6 2 8 4 3
?R??????
12
6 10 7 1 8 5 12 2 11 3 4 9
????????????
3
-1
-1
4
4
3
5
8
说明/提示
In the first test case, there are two connected graphs (the labels are indices):
The graph on the left has a diameter of , while the graph on the right has a diameter of , so the answer is .
In the second test case, there are no connected graphs, so the answer is .