We need to understand the problem. We are given a string s consisting of brackets: '(' ')', '[' ']'. We can perform moves: In each move, we select a non-empty subsequence (not necessarily contiguous) of the current string that is a regular bracket sequence (RBS) and remove that subsequence, concatenating the remaining parts in order. We can perform multiple moves. The goal: maximize the number of moves.
We need to compute the maximum possible number of moves.
Observations: In each move we remove a subsequence that is an RBS. After removal, the remaining characters are kept in order. We can repeat.
We want to maximize the number of moves, not necessarily maximize the number of removed brackets. It may be beneficial to remove small RBS's in many moves rather than one big RBS. Because each move counts as one.
Given that we can choose any subsequence (not necessarily contiguous) that forms an RBS, and we can do multiple moves, the process is similar to repeatedly extracting disjoint subsequences (since once removed, those characters are gone). But note: subsequences are selected from the current string; they might interlace? Actually, since we remove the selected subsequence, the remaining characters are concatenated. The order of removal matters because after one move, the string changes, and you can then pick another subsequence from the new string. This is effectively a sequential removal of some set of characters, each move removing a set of characters that form an RBS in the current state. However, the final result is that some characters are removed over several moves. The total set of removed characters is the union of the characters removed in each move, and these sets are disjoint (since once removed they are gone). Also, the order of removal does not affect the possibility of later removals because after removal, the remaining characters keep order. So essentially we are partitioning a subset of the indices into groups (each group forms an RBS in the order they appear in the string at the time of removal). But the condition is that each group, when considered in the original order, must be a subsequence that at the time of removal forms an RBS, but due to removals of other characters earlier, the relative order of the characters in the group may change? Actually, no: the subsequence is selected from the current string. The current string is obtained by removing previously selected characters. So the order of remaining characters is the same as original order but with some characters omitted. So when we select a subsequence from the current string, it corresponds to a subsequence of the original string that does not include any already removed characters, and the order among them is the original order. So the condition for a set of characters to be removable in a move is that when we take them in their original order (and they are currently present), they form an RBS.
Thus the overall process is: we start with the original string s. We can sequentially remove some sequences that are RBS. We can think of it as we want to partition a subset of indices into as many groups as possible such that each group, when taken in increasing order, forms an RBS, and also the groups can be removed in some order that respects that each group's characters are present at the time of removal. But if we just partition into groups, can we always schedule them? Possibly yes if we remove groups in any order? But careful: Suppose we have two groups A and B that interleave in the original string: e.g., indices: A1, B1, A2, B2. If we first remove group A, we remove characters at positions A1 and A2. The remaining string has B1 and B2 in order (since they were not removed). Then we can remove group B as an RBS if it forms one. Similarly, if we first remove group B, we then remove A. As long as each group individually is an RBS in the original order (i.e., its characters in original order form an RBS), then after removal of other characters, the group's characters remain in the same relative order and no new characters interpose (since removed ones are gone). So the group still forms the same sequence (the same bracket string) when isolated. However, note that after removal of some characters, the string from which we pick the subsequence for the next move is the concatenation of the remaining characters; we need to pick a subsequence from that string that is RBS. But if we have a set of characters that originally form an RBS, and we haven't removed any of them yet, then they appear in the current string in the same order, possibly with other characters in between. We can select exactly those characters as a subsequence (by skipping the others). So as long as those characters are still present, we can remove them as a group in one move, provided the subsequence we select is exactly those characters and that subsequence is an RBS. That condition is exactly that the string formed by those characters (in original order) is an RBS. So indeed, if we have a collection of disjoint subsets each forming an RBS (as a string), then we can remove them one by one in any order, because at each step the characters of the next group are still present and can be selected as a subsequence (skipping any remaining characters). So the problem reduces to: Given the original string s, we want to partition a set of indices (possibly not all) into as many groups as possible such that each group's characters (in order) form a regular bracket sequence. We can also leave some characters unremoved (since we don't have to remove all). We want to maximize the number of groups.
But is there any additional restriction? Could it be beneficial to not remove some characters that are part of an RBS with others because you want to split into more moves? For example, you could take a long RBS and break it into many small RBS's if possible. However, if the whole string is an RBS, you could remove it in one move, but maybe you can get more moves by breaking it into smaller RBS's. For instance, the string "()" is an RBS; you can only remove it in one move because it's the smallest non-empty RBS? Actually, "()" is an RBS; you could remove the '(' and ')' as separate moves? No, because each move must remove a non-empty subsequence that is an RBS. A single bracket is not an RBS (since empty is only allowed, and the smallest non-empty RBS are "()" and "[]" of length 2). So you cannot remove just one bracket. So maximum moves for "()" is 1. For "()()", you could remove each "()" separately as two moves, or remove both as one move? The whole "()()" is an RBS because it's concatenation of two RBS, so it's an RBS. So you could remove the whole string in one move, but that yields 1 move. However, you can do two moves: first remove one "()", then the remaining is another "()", remove it. So maximum moves is 2. So indeed, we want to partition the string into as many disjoint RBS subsequences as possible. But careful: In "()()", the two pairs are disjoint and each is an RBS; we can remove them sequentially. So the maximum number of moves equals the maximum number of disjoint RBS subsequences we can extract. However, note that the subsequences need not be contiguous; they can be interleaved? For example, consider "([])" which is an RBS. Could we extract more than one move? Possibly we could extract "()" as a subsequence: characters positions 1 and 4? That yields "()", which is RBS. After removing those, the remaining characters are '[' and ']', which form "[]", another RBS. So we can have two moves. So even though the whole string is an RBS, we can break it into two RBS's by selecting non-consecutive brackets. So the partition need not be into contiguous blocks; we can interleave groups, as long as the groups are disjoint and each forms an RBS. So the problem reduces to: given a sequence of brackets, what is the maximum number of disjoint RBS subsequences we can extract? Or equivalently, we want to cover as many brackets as possible (or not necessary all) with RBS subsequences, maximizing the number of such subsequences. Since each move removes a non-empty RBS, and we can stop anytime, we want to maximize the count.
But careful: Suppose we have a bracket that could be used in several potential RBS groups. To maximize number of groups, we might want to use small groups, like each pair "()" or "[]". However, sometimes using longer RBS might allow more groups overall? Example: "()[]" can be two groups. "([])" could be either one group (the whole) or two groups (() and [] by using positions 1,4 and 2,3). So two groups is better. So seems that using only pairs of matching brackets of same type (i.e., "()" or "[]") might be optimal because they are minimal and cannot be split further. However, can we sometimes get more than the number of such pairs? For example, consider a string with multiple brackets where we could create overlapping pairs? But we need disjoint groups. So the maximum number of moves is the maximum number of disjoint RBS subsequences we can select. Since each RBS must have at least 2 characters, and each character can be used at most once, the number of moves is at most floor(n/2). But can we achieve floor(n/2) in all cases? Not always: e.g., ")( " has no RBS at all, so 0. So the problem is similar to: we need to pair up brackets into valid matches, but note that RBS is more complex than just matching parentheses; it requires correct nesting and matching types. But for a sequence to be an RBS, it must be a well-formed bracket sequence with correct types. The simplest RBS are just a single pair of matching brackets: "()" or "[]". Also we can have concatenations: "()[]" is an RBS but can be split into two moves. So to maximize number of moves, it seems beneficial to break any longer RBS into smaller ones. However, can we always break any RBS into a collection of disjoint pairs of matching brackets? Not necessarily: consider "[()]". This is an RBS. Can we split it into two RBS? Let's see: pick subsequence positions 1 and 4: "[]"? Actually positions: 1='[', 2='(', 3=')', 4=']'. If we pick 1 and 4, that's "[]" which is RBS. Then remaining 2 and 3 are "()", which is RBS. So yes, two moves. So any RBS that has outer brackets matching? For "[()]", we used the outer pair and the inner pair. That works because they are properly nested and types match. What about "(())"? Positions: 1='(', 2='(', 3=')', 4=')'. Could we get two moves? Choose subsequence positions 1 and 4: that gives "()", RBS. Remaining positions 2 and 3 give "()", RBS. Yes. So any perfectly nested structure can be split into outer and inner pairs if the outer brackets are matching and the inner forms an RBS? Actually, for "(())", inner is "()" and outer is "()" as well. So we get two pairs. What about "([])" we already did. So it seems that any RBS can be decomposed into a set of disjoint pairs? Not necessarily; consider "(()[])"? Let's test: s = '(', '(', ')', '[', ']', ')'. This is RBS? It is '(' + RBS? inner: "()[]" which is RBS, then outer ')', so yes "(()[])" is RBS. Can we split into disjoint RBS pairs? Possibly: outer pair positions 1 and 6 -> "()"? But type: '(' at 1, ')' at 6: matching? '(' and ')' match, yes. Then inner: positions 2 and 3 -> "()", positions 4 and 5 -> "[]". So three pairs total. That works. So it seems any RBS can be decomposed into matching pairs by taking each opening bracket with its corresponding closing partner in the parse tree? Actually, in a well-formed bracket sequence, each opening bracket has a matching closing bracket. If we take each matched pair as a separate RBS, they are disjoint and each is either "()" or "[]". However, careful: In the standard parse of an RBS, the pairs are nested and not overlapping. The matched pairs are naturally disjoint (each bracket belongs to exactly one pair). Indeed, in any well-formed bracket sequence, the brackets can be uniquely paired: each opening matches with exactly one closing, and they do not cross. So the string itself, if it is an RBS, can be partitioned into these matched pairs (the pairs are the matching parentheses and square brackets). But note: In a concatenation of RBS's, the pairs are still non-crossing; the matching is within each concatenated component. So the natural pairing yields disjoint pairs that are "()" or "[]". And each such pair is itself an RBS. Therefore, any RBS can be partitioned into such atomic pairs.
Thus, if we are able to select any set of disjoint pairs (matching an opening with a closing of the same type, and they must be correctly matched in the sense that when you consider the whole string, the pairs might not be "matching" in the usual stack sense if there are interleaved brackets of different types? Actually, to be a valid RBS, the subsequence itself must be well-formed. So if we pick an opening '(' and a later closing ')', but there might be other brackets between them that are not selected, that's okay as long as the subsequence of the two brackets is "()" which is RBS. However, if there is an opening '[' between them, that's fine because we are not selecting it. So the condition for a pair (i,j) to form an RBS "()" or "[]" is simply that s[i] is '(' and s[j] is ')' (or s[i]=='[' and s[j]==']'), and i<j. There's no additional constraint about the content between them because we are selecting just these two brackets as the subsequence. So any '(' and ')' can be paired as a move, provided they are in the correct order and not already used. Similarly for '[' and ']'. So the problem appears to be: We have a sequence of brackets; we want to maximize the number of moves, each move removes a subsequence that is an RBS. Since we can always break any RBS into such atomic pairs (each a move), the maximum number of moves is essentially the maximum number of such pairs we can extract, because we can use each move to remove a single pair "()" or "[]". However, is it always optimal to use only atomic pairs? Could there be a scenario where using a longer RBS allows us to have more total moves than just pairing individually? Since each move removes at least 2 characters, the total number of moves is bounded by floor(total_removed/2). To maximize count, we want to maximize the number of moves, which means we want to maximize the number of disjoint pairs we can select, because each move can be a pair. However, there might be a case where we cannot pair all brackets into such simple pairs because of ordering constraints: we need to select disjoint pairs (each pair consists of an opening before a closing of same type) and they must be disjoint (each index used at most once). This is essentially a maximum matching problem on a sequence: we want to select as many pairs (i,j) with i<j, s[i] opening, s[j] closing of same type, and no index used twice. This is similar to counting how many matching parentheses and brackets we can pair greedily: we can treat '(' and ')' separately from '[' and ']'? But careful: Since pairs must be of same type, we can treat each type independently? However, the indices are interleaved; but if we pair '(' with ')' and '[' with ']', these are independent because they involve different characters. The only constraint is that each character can be used at most once. So we can count for each type separately: we want to pair as many '(' with ')' as possible, respecting order (each '(' must come before its paired ')') and not reusing indices. Similarly for square brackets. Since the characters are distinct, we can simply compute the maximum number of valid pairs for each type separately, and sum them. But is there any interaction? Could using a '(' for a pair prevent using a '[' that could have been paired with a later ']' because of ordering? Since they are independent sets, pairing one type does not affect the other because they use different characters. However, the ordering constraint for each type is separate: we need to match opening of that type with closing of the same type, in order. That's like: given a string, consider only the '(' and ')' characters, ignore others. The maximum number of matched pairs in such a subsequence (where we can skip characters) is essentially the minimum of count of '(' and count of ')' after considering ordering? Actually, if we have a sequence of '(' and ')', the maximum number of valid parentheses pairs (non-crossing, each '(' matched with a later ')') is the classic problem: we can match greedily: use a stack: whenever we see '(', push; when we see ')', if stack not empty, pop and count a pair. This yields the maximum possible number of pairs because each '(' can only be used once and each ')' can only be used once, and the greedy ensures we match the earliest '(' with a later ')', which is optimal. This works for parentheses ignoring other characters. For square brackets similar.
So the answer would be: For each test case, compute count1 = number of matched pairs for '(' and ')'; count2 = number of matched pairs for '[' and ']'; answer = count1 + count2.
But is this always optimal? Could we sometimes get more moves by using a longer RBS that includes both types and yields more moves than the sum of these atomic pairs? For example, suppose we have string: "([])" we got 2 pairs using atomic pairs: '(' matched with ')', '[' matched with ']'. That's 2 moves. Could we get 3 moves? No, because only 4 characters, max moves floor(4/2)=2. So that's fine.
Consider string: "([)]". This is not a valid RBS as a whole, but we can still extract subsequences. The example output for "([)]" is 2. Let's test our approach: Only '(' and ')'? Sequence of '(' and ')' in order: positions 1='(' and 3=')' => we can match one pair. '[' and ']': positions 2='[' and 4=']' => one pair. Sum =2. That matches output.
Consider string: ")]([" output 0. Our method: Only ')' and '('? The sequence of '(' and ')' is: positions: 2='(', 1=')'? Actually order: s = ')', '(', ')', '['? Wait example: ")]([" from input: line 4: ")]([". Let's see: characters: 1=')', 2='(', 3=')', 4='['? Actually ")]([" -> characters: 1: ')', 2: '(', 3: ')', 4: '['? Wait ")]([" is four characters: first ')', then '(', then ')', then '['? Actually the string: ")]([" - it likely is ')', '(', ')', '['? But it says ")]([" - after the backslash? Actually it's typed as ")]([" which is: ')', '(', ')', '['? But the fourth char should be '['? The string in example is ")]([" but that would be: character 1: ')', char2: '(', char3: ')', char4: '['? That seems off because ")]([" should have four characters: ')', '(', ')', '['? But the example output is 0. Let's check: They gave input:
5
()
([)]
)]([
)[(]
I think the fourth line is ")](["? Actually the sample:
5
()
([)]
)]([
)[(]
Yes, the fourth is ")]([" (four characters: ')', '(', ')', '['? But that seems mismatched because the closing bracket for '[' would be ']', not present. Anyway, our method: For '(' and ')' sequence: characters: at positions: 2='(', 1=')', 3=')'? Actually order matters: we need to consider the order they appear. The string ")]([" has: index1=')', index2='(', index3=')', index4='['. So the sequence of '(' and ')' in order: '(' at index2, ')' at index1? Actually order by index: at index1: ')', index2: '(', index3: ')', index4: '['. So the '(' and ')' characters in order: index1: ')', index2: '(', index3: ')'. So the subsequence is: ')','(',')'. How many pairs can we form? We can try to match '(' with a later ')': there is '(' at index2, and ')' at index3, so that's one possible pair. However, we also have a ')' at index1 which is before the '(', cannot be paired with that '(' because it's before. Could we pair index1 ')' with some '('? There is no '(' before index1, so no. So maximum pairs = 1? But wait, our greedy algorithm for parentheses: traverse the string, maintain a counter for '(' (or stack). When we see '(', push; when we see ')', if stack not empty, pop and count. But careful: In classic parentheses matching, we require '(' before ')'. If we traverse the string ")]([" in order: first char ')', stack for '(' is empty, so ignore. Then '(', push. Then ')', pop -> count one. Then '[' (ignore). So we would count 1 pair. For square brackets: only '[' at index4, no ']', so 0. Sum=1. But expected output is 0. So something is wrong. Let's double-check the fourth string: ")]([" maybe it's actually ")]([" but I recall the sample from Codeforces problem "1472C? Actually this problem appears to be from Codeforces: "1462C? Not sure. Let's re-express: The input example:
5
()
([)]
)]([
)[(]
The fourth line is ")](["? That seems odd because a regular bracket sequence uses only '(', ')', '[', ']'. So ")]([" contains characters: ')', '(', ')', '['? That's valid characters. But maybe I misread: Could be ")]([" is actually three characters? No, it's four. Let's check: They wrote ")]([" . Usually they'd use backslash for escape? In text, ")]([" might be displayed as ")]([" meaning a string of four characters: ')', ']', '(', '['? Actually the text ")]([" includes a backslash? In plain text, it's likely ")]([" where the second character is ']'? Wait, the string is ")]([" . The characters: The first is ')'? Actually, it's: a right parenthesis ')', then a right bracket ']', then a left parenthesis '(', then a left bracket '['? That would be: ) ] ( [ . That is ")](["? Actually the string is typed: ) ] ( [ . In the sample it's written as ")]([" but that would be: character1 = ')', character2 = ']', character3 = '(', character4 = '['? Because ")](" would be ')', ']', '(' and then the last '['? But the string is ")]([" with four characters: after the third character '(' there is '['. So indeed it's ')', ']', '(', '['. That makes more sense: The fourth line is ")]([" meaning: first ')', second ']', third '(', fourth '['. That is a sequence of closing then opening brackets of both types. And there is no matching pair because we have only closing then opening of both types, but we need an opening before a closing. So our greedy would for '(' and ')' sequence: characters in order: index3='(', no ')' after? Actually there is no ')' after index3? The string has ')', ']', '(', '['. So for parentheses: we have ')' at index1 and '(' at index3. So sequence: ')','(' . That cannot form a pair because '(' must come before ')'. So maximum pairs = 0. For square brackets: ']' at index2, '[' at index4. That's ']' then '[', cannot pair because '[' must come before ']'. So 0. Sum=0. That matches output. Good.
So indeed, the greedy per type works: count pairs for '(' and ')', and pairs for '[' and ']', summing them.
Now the fifth example: ")[(]" . Let's parse: characters: 1=')', 2='(', 3='[', 4=']'? Actually ")[(]" is: ')', '(', '[', ']'? Wait ")[(]" includes four characters: first ')', second '(', third '[', fourth ']'? Actually the string is ")[(]" - that likely is: ')', '(', '[', ']'? But it's written as ")[(]" . Usually it would be: ')', '(', '[', ']'? Actually ")[(]" would be: char1=')', char2='(', char3='[', char4=']'? No, "[(" is reversed? Let's check: The example output is 1. Our method: For parentheses: we have ')' at index1, '(' at index2. Sequence: ')','(' => cannot pair because '(' after ')', but we need '(' before ')'. So 0 pairs. For square brackets: '[' at index3, ']' at index4 => that can pair as "[]". So 1 pair. Sum=1. Matches.
Thus the solution appears to be simply counting the number of matched pairs for each type separately using a simple greedy.
But is this always optimal? Let's think more deeply. Could there be a scenario where using a longer RBS (not just a simple pair) allows us to get more total moves than the sum of simple pairs? Consider that each move removes at least 2 characters. The total number of moves is at most floor(N/2). The sum of simple pairs can achieve at most floor(N/2) as well (since each pair uses two characters). So the maximum possible moves is floor(N/2). But sometimes we might not be able to achieve floor(N/2) because of mismatched brackets. The greedy per type gives the maximum number of disjoint pairs of matching brackets of same type. This is essentially the maximum number of moves if we restrict each move to be a single pair. But could we sometimes get more moves by using moves that remove more than 2 characters but allow additional moves with leftover characters that otherwise would be unusable? For example, suppose we have a string where the greedy per type gives k pairs, but the total number of characters used is 2k. The remaining characters (N-2k) are such that they cannot form any RBS even together with some of the already used ones? But if we used some of them in a longer RBS that includes multiple characters, perhaps we could incorporate some otherwise unmatched brackets into a valid RBS, thereby increasing the total number of moves? However, each move is a single RBS; if we use a longer RBS that consumes, say, 4 characters, that's one move. If instead we could break it into two pairs, that's two moves, which is better. So longer RBS is never better for maximizing move count if we can break it into pairs. But could there be a scenario where we cannot break a longer RBS into pairs because the pairs would conflict with each other? For instance, consider the string: "([)]". We can get two pairs as shown. That's breaking the string into pairs. That's optimal. Could there be a string where no two disjoint pairs exist, but a larger RBS exists? For example, consider "([])" we have two pairs. That's max. What about "((]]"? That is '(' '(' ']' ']'? That cannot form any RBS because we need matching types. Could there be a string like "([)]" we already did. I'm trying to find a counterexample where sum of greedy per type is less than the maximum number of moves possible if we allow longer RBS. For instance, suppose we have: "(()]". Let's examine: s = '(', '(', ')', ']'. Greedy per type: parentheses: we have '(' '(' ')' -> can form one pair (matching one '(' with the ')'). The other '(' remains unpaired. Square brackets: ']' alone, no '['. So total =1. However, could we do more than 1 move? We could try to extract an RBS that is not just a pair. For example, consider subsequence: positions 1,2,3,4? That's "(()]" which is not RBS. Subsequence 1,3 -> "()" is RBS; that's a pair. After removal, remaining characters: position 2='(', position 4=']' -> "(]" which is not an RBS, no subsequence RBS (except maybe empty). So total moves=1. Alternatively, could we first remove some other RBS? The only possible RBS are "()" from positions (1,3) or (2,3). If we remove (2,3) as "()", remaining: pos1='(', pos4=']' -> "(]" no RBS. So 1. So answer=1 matches greedy.
Another scenario: "[(])". s = '[', '(', ')', ']'? Actually "[(])" is four characters: '[', '(', ')', ']'. Greedy per type: parentheses: '(' and ')' can pair => 1. Square brackets: '[' and ']' can pair => 1. Sum=2. But can we actually get 2 moves? Let's try: First remove "()" using positions 2 and 3, remaining "[ ]" => "[]" => second move. So yes 2 moves. So greedy works.
Consider "([)]" we saw sum=2 works.
Now consider something like "()[]" -> sum=2. Max moves 2 (each pair). Could we get 3 moves? Only 4 chars so max 2.
Consider a longer string: "()()()" -> 3 pairs => 3 moves.
Now what about strings where we have interleaving like "([)]" we already did. So far, greedy per type seems to give the answer.
But is there any situation where using a longer RBS could allow us to use some characters that would otherwise be unmatched and thus increase count? For example, suppose we have an odd number of characters, but maybe by combining them in a longer RBS we could free up a character to be used in another RBS? Wait, each character can only be used once. So the total number of moves is at most the total number of matched pairs (in the sense of bracket matching) but perhaps there is a possibility to have a move that uses, say, 3 pairs concatenated (like "()()()") and that would be one move, but if we break into three moves we get more moves. So never beneficial to combine.
But what about a scenario where simple pairs are not possible because the opening and closing are in the wrong order for each type, but a mixed RBS could be formed? For instance, consider string: ")(" . No pairs because '(' after ')', but also the whole string ")(" is not RBS. So 0 moves. That's greedy sum=0.
Consider string: "[])([]". Let's compute: s = '[', ']', ')', '(', ']'? Wait "[])([]" is 6 chars: 1='[',2=']',3=')',4='(',5='[',6=']'? Actually "[])([]" = '[',']',')','(','[',']'? That gives parentheses: positions 3=')',4='(' -> sequence: ')','(' -> no pair. Square brackets: positions 1='[',2=']' pair, positions 5='[',6=']' pair -> total 2 pairs. So greedy sum=2. But could we do more? Maximum moves floor(6/2)=3? Is it possible to get 3 moves? Perhaps by using a longer RBS that mixes types to pair the middle ')(' in some way? For example, consider subsequence: positions 2,3,4,5? That's "])()"? Not RBS. What about positions 1,3,4,6? That's "[)()]"? Not RBS. How about positions 1,3,5,6? "[)[]"? Not. Could we do three moves? Possibly if we could use the middle ')(' as part of some RBS. But they are opposite direction: '(' after ')'. The only way to make an RBS using these two is to have '(' before ')', not the other way. Could we combine them with brackets of other types to make a valid RBS? For example, a sequence like "([])" is RBS. That uses '(' then '[' then ']' then ')'. In our string, we have at positions: 4='(', 5='[',6=']',? we would need a closing ')' after the ']' but we have ')' at position 3 before. Could we reorder via subsequence? Subsequence must preserve order, so we cannot reorder. To get "([])" we need '(' then '[' then ']' then ')'. In our string, we have '(' at 4, '[' at 5, ']' at 6, and we could use ')' at some later position? There is no later ')', only at 3 before. So cannot. What about "[()]"? Would be '[' then '(' then ')' then ']'. We have '[' at 1, '(' at 4, ')' at 3 (but order: 1='[', then we need '(' after '['. There is '(' at 4, okay. Then need ')' after '(': we have ')' at 3, but 3 is before 4, so can't. So not possible. So likely 2 is max.
But can we get 2? Yes, as greedy. So it's fine.
Now consider a more complex string: "([)]". Already gave 2.
Now consider "(([[))]]". Let's test: s = '(', '(', '[', '[', ')', ')', ']', ']'. Greedy per type: parentheses: '(' '(' ')' ')' -> can match two pairs? Actually, traverse: we have a counter for '('? Let's simulate: When scanning whole string: for '(' and ')', ignore others? Actually we need to consider only '(' and ')'. The sequence of '(' and ')' in order: positions 1='(',2='(',5=')',6=')' -> that's "(() )"? Actually sequence: '(' '(' ')' ')' -> can we form two pairs? Using greedy: count for '(' and ')'. Use stack: when see '(' push; see ')' if stack not empty pop and count. For sequence: '(' push, '(' push, ')' -> pop => count1, ')' -> pop => count2. So 2 pairs. For square brackets: positions 3='[',4='[',7=']',8=']' -> similarly 2 pairs. Sum=4. Total characters 8, so 4 moves possible? But can we actually achieve 4 moves? Let's try: We could pair each '(' with a ')', but note that the parentheses are interleaved with square brackets. However, we can select subsequences: For first pair of parentheses, we could choose positions 1 and 5: '(' and ')' -> "()". For second pair, positions 2 and 6: '(' and ')' -> "()". For square brackets: positions 3 and 7: '[' and ']' -> "[]". For second square: positions 4 and 8: '[' and ']' -> "[]". All disjoint and valid. So 4 moves. Good.
Now consider a tricky string: "()[](" (5 chars). Greedy: parentheses: '(' at 1, ')' at 2 => one pair. Also parentheses: '(' at 5 alone, no closing => so 1. Square brackets: '[' at 3, ']' at 4 => one pair. Sum=2. Could we get more than 2 moves? Max moves floor(5/2)=2. So 2 is max.
Now consider "([)]". Already 2.
Now consider a scenario where there are many opening brackets of one type and many closing of the other, and maybe mixing them can produce an RBS that uses both, potentially allowing more total moves than just matching same-type pairs. For example, suppose we have many '(' and many ']' but few '[' and ')'. Could combining them into longer RBS produce extra moves? But an RBS requires that brackets match correctly: '(' must pair with ')', '[' with ']'. So a sequence like "(]" is not RBS. So mixing types doesn't create a valid pair. So you cannot pair '(' with ']' or '[' with ')'. So the only way to use a character is to pair it with a matching counterpart of the same type. So indeed the moves are limited by the number of matching pairs of same type. However, could there be a scenario where using a longer RBS that includes multiple pairs allows us to use some characters that would otherwise be left unmatched because of ordering constraints? For example, consider a string where for parentheses, the number of '(' and ')' is equal, but they are interleaved such that the greedy algorithm yields fewer pairs than the total count of '(' (or ')')? Actually, for parentheses alone, when ignoring other characters, the greedy algorithm (stack) gives the maximum number of matched pairs. That is a known fact: In a sequence of '(' and ')', the maximum number of matched pairs (non-crossing, each '(' before its ')') is exactly the number of pairs you can form by matching each ')' with the most recent unmatched '(' (greedy). This yields the maximum because any valid matching must respect that each ')' can only be matched to a '(' before it, and greedy uses the closest unmatched '(' which leaves more '(' for later ')'. So it's optimal. So per type, greedy yields the maximum number of disjoint pairs (i.e., matches) you can form from that type's characters, ignoring others. Since characters of other types are irrelevant for that type, the maximum number of pairs of that type is independent. However, could using some characters in a mixed RBS allow you to "use" a '(' and a ')' that could not be paired directly because of intervening characters of other types? But the greedy algorithm for parentheses already works on the subsequence of '(' and ')', ignoring others. Intervening characters do not affect the ability to match '(' and ')' as long as the order of '(' and ')' in the original string is preserved. The presence of other characters does not hinder forming a pair, because we can skip them. For example, string "( [ ) ]". The sequence for parentheses: '(' then ')', but there is a '[' between them. That's okay; we can still pair '(' with ')' by skipping the '['. So greedy would count that as one pair. So no issue.
Thus, it seems the maximum number of moves is simply the sum over types of the maximum number of matching pairs that can be formed from that type's brackets, considered independently.
But wait: Could there be a scenario where using a longer RBS that includes both types allows us to create an extra move using some characters that would otherwise be unusable because for each type individually they are unmatched? For instance, suppose we have an opening '(' and a closing ']' that cannot pair, but by combining with other brackets we might create a valid RBS that uses them in different roles? However, in an RBS, each opening must be closed by a matching bracket of the same type. So a '(' must be closed by ')'. So a '(' can never be matched with a ']'. So if there is a '(' with no ')' after it (or before it? Actually need '(' before ')'), that '(' is unusable. Similarly for '[' without ']'. So such characters cannot be part of any RBS, because any RBS containing them would require a matching closing bracket of the same type. If none exists in the string (in the correct order), then they can't be used. So they are useless. So they don't affect count.
What about a scenario where due to interleaving, we might be forced to use some characters in a particular way that reduces the number of pairs? But since we can choose any subsequence for each move, and moves are sequential, we can always extract pairs greedily without conflict. For each type, we can simulate: maintain a counter for unmatched openings of that type. As we scan the string, when we see an opening of that type, we increment; when we see a closing of that type, if there is an unmatched opening, we can pair this closing with one of them. The specific choice of which opening to pair with which closing may affect ability to pair other types? Since the characters are distinct, pairing one type does not affect the availability of characters of another type. So we can treat them independently.
Therefore, the answer seems straightforward: For each test case, compute:
ans = min(count('('), count(')'))? Not exactly, because order matters. Example: ")(" has one '(' and one ')', but min is 1 but answer is 0. So we need to consider order.
We need to compute the maximum number of pairs (i<j) such that s[i] is '(' and s[j] is ')', and each index used at most once, and pairs are non-crossing? Actually, they don't need to be non-crossing? In the matching sense, if we have two pairs (i1,j1) and (i2,j2), they must be disjoint indices. Could they cross? i1 < i2 < j1 < j2. That would be crossing. Is such crossing allowed? For disjoint subsequences, if we have two pairs that cross, can we still select them as separate moves? Yes, because we can remove one pair first, then the other. But careful: If we have crossing pairs, say indices: '(' at 1, ')' at 3, and '(' at 2, ')' at 4. If we first remove pair (1,3), the remaining string has indices 2 and 4 (since we remove 1 and 3). After removal, the order is index2 then index4, which are '(' and ')', which can be removed as a pair. So crossing pairs are allowed. However, the greedy algorithm for parentheses (using a stack) typically produces non-crossing matches (the standard matching). But if we are allowed to match any '(' with any later ')', not necessarily in a stack-like manner, can we get more pairs? For a sequence of '(' and ')', the maximum number of disjoint pairs (i,j) with i<j, s[i]='(', s[j]=')' is actually the minimum of the total counts of '(' and ')', but also constrained by the fact that we cannot match a '(' that appears after a ')'? Actually, consider the sequence: ")(" . There is one '(' and one ')', but can we form a pair? We need an opening before closing. '(' appears at position 2, ')' at position 1. No pair possible. So the maximum is not simply min counts; order matters. The maximum number of such pairs is equal to the number of times we see a ')' that has at least one '(' before it that hasn't been used. This is exactly what the greedy stack algorithm counts. That algorithm yields the maximum possible number of pairs, and it produces a set of pairs that are non-crossing? Actually, the greedy algorithm pairs each ')' with the most recent unmatched '('. That yields non-crossing pairs? In standard parenthesis matching, it yields non-crossing pairs because it's like matching parentheses in an expression. But if we allow any pairing (crossing), could we possibly get more pairs than the greedy algorithm? Let's test with a sequence: "(()". This has two '(' and one ')'. Greedy yields 1 pair (matching the last '('? Actually, scanning: '(' -> push1; '(' -> push2; ')' -> pop => pair with the second '(' => 1 pair. Could we also match the first '(' with the ')'? That would be the only possibility, still 1 pair. So no difference.
Consider: ")(()". Sequence: ')','(','(',')'. Greedy: on ')', stack empty, ignore; '(' push; '(' push; ')' pop => 1 pair. Could we get 2 pairs? We have two '(' and two ')', but one ')' is before the '('s. The available pairs: we could match the first ')' with the second '('? But need opening before closing; can't. So max 1. So greedy ok.
Consider: "()()" greedy yields 2 pairs. Good.
Consider: "(())" greedy yields 2 pairs? Let's see: '(' push1; '(' push2; ')' pop2 => pair1; ')' pop1 => pair2. So 2 pairs. That's maximum.
Now consider a more complex sequence where crossing might allow more pairs? Suppose we have: "(()())". That's standard, greedy yields 3 pairs.
I think for a sequence consisting only of '(' and ')', the maximum number of disjoint pairs (i.e., a matching where each '(' is matched to a later ')', and no index used twice) is exactly the number of pairs found by the greedy algorithm that matches each ')' with the most recent unmatched '(' (or equivalently, the number of ')' that have at least one unmatched '(' before them). Because any valid matching must respect that each ')' can only be matched to a '(' before it, and if we process left to right, whenever we see a ')', if there is any unmatched '(' before, we can match it. The greedy choice (matching with the most recent) doesn't reduce the total count because it leaves earlier '(' available for later ')', which is optimal. So the greedy count is maximum. This is classic: the length of the longest regular bracket subsequence (not necessarily contiguous) for only parentheses is 2 * (number of matched pairs) from this algorithm. So indeed maximum pairs = that count.
Now for square brackets, same.
Since the two types are independent, the total maximum moves = for each type, compute the matched pairs count using a simple left-to-right counter for that type, and sum them.
But we must be careful: Could there be an interaction where using a bracket in a pair of one type prevents using another bracket in a pair of the other type, because the removal order might affect the ability to select subsequences? As argued, since the sets are disjoint, we can always schedule the moves to remove all pairs eventually. However, consider a case where we have crossing between types that might cause a problem if we remove one pair first? Let's examine: Suppose we have string: "([)]". Our plan: match '(' with ')' (positions 1 and 3) and '[' with ']' (2 and 4). These pairs cross: (1,3) and (2,4) cross. We can first remove pair (1,3) -> remove characters at 1 and 3. The remaining string is positions 2 and 4: '[' and ']' => "[]", we can remove as second move. Works. If we first remove (2,4), remaining (1,3): "()" works. So fine.
Consider a more complex crossing: "([{)]}" but we only have two types, so okay.
Thus it appears the answer is sum of matches per type.
But wait: The problem statement says: "In one move you can choose a non-empty subsequence of the string s (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order." This allows selecting any subsequence, not necessarily consisting of a single pair. So we can also remove longer sequences. But we have argued that using only pairs is optimal. However, is it always possible to partition the selected pairs into moves such that each move is exactly one pair? Yes, because each pair is an RBS. So we can plan to remove them one by one.
But is there any scenario where the greedy per type count might be less than the maximum number of moves, because maybe by combining some characters into a longer RBS we could free up other characters to form additional moves that would otherwise be impossible due to crossing? For instance, suppose we have a string where the greedy algorithm for parentheses gives k pairs, but there exists a strategy that yields >k moves overall, perhaps using some moves that are not just pairs but include both types, and then after removal, we can create more pairs? However, since the greedy per type count already counts the maximum possible pairs from each type, any move that uses multiple pairs reduces the number of moves because it consolidates several pairs into one move. So that wouldn't increase the count. The only potential for more moves is if we can get more than the maximum number of pairs per type, i.e., we can use some brackets in a way that yields more than one move per two characters? Not possible because each move uses at least two characters. So the total number of moves is at most total number of characters used / 2. The greedy per type uses exactly 2 * (count_pairs_parentheses + count_pairs_square) characters. Could there be a scenario where we can use some characters that are not usable in any pair (due to order) but can be used in a longer RBS that includes them and also includes some other characters, resulting in a move that uses, say, 3 characters? But an RBS must have even length? Actually, regular bracket sequences always have even length because each opening is matched with a closing. So length is even. So any RBS uses an even number of characters. So any move uses an even number of characters. So the total number of characters used across all moves is even. The greedy per type uses the maximum possible number of characters that can be paired in a matching? Not exactly: There might be characters that cannot be paired in simple same-type pairs due to order, but could be part of a longer RBS that includes other characters such that overall the RBS is valid and uses those characters. For instance, consider a string: ")(" we saw no pair. But could there be a longer RBS that uses both characters? The only RBS are even length; but ")(" length 2, is it an RBS? No. So cannot use them. So they remain unused.
Now consider a more subtle string: ")(()". We have: positions: 1=')',2='(',3='(',4=')'. Greedy per type: parentheses only: we have a ')' at start, ignore; then '(' push; '(' push; then ')' pop => 1 pair. So one pair uses indices 3? Actually, greedy matches the second '(' with the last ')', leaving index2 '(' unmatched, and index1 ')' unmatched. Could we do better than one move? Could we make two moves? Suppose we try to remove a subsequence that is RBS using all four characters? The whole string ")(()" is not RBS. Could we remove two moves? For two moves we need two disjoint RBS each of even length. Total characters used would be 4, so exactly two moves each of length 2 if possible. But we cannot form two pairs because of ordering. Could we form one RBS of length 4 and another none? That's one move. Could we form one RBS of length 2 and another of length 2? The only possible pairs are: (2,4) -> "()", (3,4) -> "()". They share index4. So cannot have two disjoint pairs because there's only one ')'. So maximum moves = 1, matches greedy.
Now consider a string with both types: "([)]". Greedy gives 2 pairs, as we argued, and we can achieve 2 moves. Good.
Now consider: "((]))". Let's think: s = '(', '(', ']', ')', ')'? Actually "((]))" is 5 characters: '(', '(', ']', ')', ')'? Wait "((]))" would be: positions: 1='(',2='(',3=']',4=')',5=')'? That's parentheses: 1='(',2='(',4=')',5=')' => sequence: '(' '(' ')' ')' -> can get 2 pairs? Greedy: on '(' push; '(' push; ')' pop => pair1; ')' pop => pair2 => 2 pairs. Square: ']' alone, no '[' => 0. So total 2. But can we actually get 2 moves? Let's try: Pair1: (1,4) -> "()". Pair2: (2,5) -> "()". These are disjoint. After removing them, left is ']' at position3, which cannot be used. So 2 moves. Works.
Now consider: "[(])". This is 4 characters: '[', '(', ')', ']'. Greedy: parentheses: '(' and ')' -> 1; square: '[' and ']' -> 1; total 2. Works.
Now consider: "([)][". s = '(', '[', ')', ']', '['. Length 5. Greedy: parentheses: '(' at1, ')' at3 => pair =>1. Square: '[' at2, ']' at4 => pair1; '[' at5 alone =>0. So total 2. Can we achieve 2 moves? Remove pair (1,3) -> "()", remaining: positions 2,4,5 = "[ ][", that is "[][" which is RBS? "[][" is concatenation of "[]" and "[", but "[][" not a valid RBS because the last '[' has no matching ']'? Actually "[][" as a string: '[' ,']' ,'[' . That's not a valid RBS because it's length 3 odd, but could we extract a subsequence that is an RBS? The remaining string "[][" has characters: index2='[', index4=']', index5='['. We can select subsequence [2,4] -> "[]", which is RBS, that's second move. So 2 moves. Works.
Now what about a scenario where the greedy per type count might be less than the maximum possible number of moves because we might be able to use some characters in mixed RBS that allow us to "reorder" the unmatched characters? But since we cannot reorder, any RBS must respect the original order. So the only way to incorporate an unmatched opening of one type is to match it with a closing of the same type that appears after it. If there is none, it's impossible. Could combining with other brackets create a scenario where that opening gets matched indirectly? No, because the definition of RBS requires each opening to be closed by a matching bracket of the same type, so it must have a corresponding closing of the same type somewhere after it in the subsequence. So if there is no closing of that type after it in the whole string, it cannot be used in any RBS. Similarly, a closing bracket needs a matching opening before it.
Thus, the problem reduces to: For each type, find the maximum number of disjoint matching pairs (opening before closing). This is independent.
Hence answer = number of matched '(' and ')' + number of matched '[' and ']'.
We can compute this by scanning the string once, maintaining two counters: open1 for '(' and open2 for '['. When we see '(', increment open1. When we see ')', if open1>0 then open1-- and ans++. When we see '[', increment open2. When we see ']', if open2>0 then open2-- and ans++. This yields the sum.
Check with examples:
-
"()": '(' -> open1=1; ')' -> open1>0 => ans=1, open1=0. Output 1.
-
"": '[' -> open2=1; ']' -> open2>0 => ans=1, open2=0; '(' -> open1=1; ')' -> ans=2, open1=0. Output 2.
-
"([)]": '(' -> open1=1; '[' -> open2=1; ')' -> open1>0 => ans=1, open1=0; ']' -> open2>0 => ans=2, open2=0. Output 2.
-
")]([" : first ')', open1=0 -> ignore; ']', open2=0 -> ignore; '(' -> open1=1; '[' -> open2=1; no more closings. ans=0. Output 0.
-
")[(]" : ')' -> open1=0; '(' -> open1=1; '[' -> open2=1; ']' -> open2>0 => ans=1. Output 1.
Matches sample.
Thus the solution is straightforward.
But is there any tricky case where this fails? Let's try random.
Consider "(([[))]]" earlier gave ans=4.
Consider "(([))]"? s = '(', '(', '[', ')', ')', ']'? That is 6 chars. Greedy: '(' '(' -> open1=2; '[' -> open2=1; ')' -> open1>0 => ans=1, open1=1; ')' -> open1>0 => ans=2, open1=0; ']' -> open2>0 => ans=3, open2=0. So ans=3. Can we achieve 3 moves? Need to check if we can actually get 3 disjoint RBS. Possibilities: perhaps we can get two '(' pairs and one '[]' pair. But note: the string: positions: 1='(',2='(',3='[',4=')',5=')',6=']'. We can pair: (2,4) -> "()", (1,5) -> "()", and (3,6) -> "[]". All disjoint, works. So 3 moves. Good.
Consider "([)][("? s = '(', '[', ')', ']', '[', '(' . length6. Greedy: '(' open1=1; '[' open2=1; ')' -> ans1 (parentheses) => ans=1, open1=0; ']' -> ans2 => ans=2, open2=0; '[' open2=1; '(' open1=1; no closings => ans=2. Could we get more? Possibly by using different pairing? We have one '(' and one ')' used already, but we have an extra '[' and '(' at end without closings. So max moves 2. Could we do a longer RBS that uses the last '(' and maybe earlier ')'? But the ')' is already used? But if we instead pair the first '(' with the last ')'? There's no last ')', only one ')' at position3. So only one possible ')', so at most one parentheses pair. So max moves 2 (one parentheses pair, one square pair). So ans=2.
Consider "([)][)]"? Not needed.
Thus solution is simple.
But wait, there is nuance: In the problem, they define RBS as either empty, '(' + RBS + ')', '[' + RBS + ']', or RBS + RBS. This is the standard definition of regular bracket sequence (also called correct bracket sequence). It allows concatenation. So a subsequence that is RBS can be of any even length, as long as it's well-formed. The greedy per-type pair approach essentially uses only length-2 RBS. That's fine.
Now, is there any scenario where using a longer RBS could yield a higher number of moves than the sum of the greedy per-type pairs? That would require that there exists a set of disjoint RBS such that the total number of RBS is greater than the sum of per-type matched pairs. Since each RBS must contain at least one pair of matching brackets (maybe more). The total number of RBS is at most the total number of matched pairs across all types, because each RBS consumes at least one matched pair. But could there be an RBS that does not contain a full matched pair? No, the smallest non-empty RBS is length 2, which is exactly one matched pair. So each move corresponds to at least one matched pair. So the total number of moves ≤ total number of matched pairs (counting each pair as a pair of matching brackets). But what is a "matched pair"? It is an opening and a closing of the same type in the correct order (opening before closing) that are not necessarily adjacent and may be part of different moves. However, note that one RBS could contain multiple matched pairs. So if we count the total number of matched pairs used across all moves, that total is at least the number of moves (since each move contributes at least 1 matched pair). But the maximum total number of matched pairs we can extract from the string (i.e., the maximum number of disjoint (i,j) pairs with s[i] opening, s[j] closing same type) is exactly the sum of per-type greedy counts. This is the maximum number of matched pairs we can have overall (each character used at most once). That number is an upper bound on the total number of matched pairs used. Since each move needs at least one matched pair, the number of moves ≤ that maximum. But can the number of moves be strictly greater than the number of matched pairs? No, because each move uses at least one pair, so number of moves ≤ total pairs used ≤ maximum pairs. So the maximum possible moves ≤ maximum pairs. On the other hand, we can achieve exactly maximum pairs by using each pair as a separate move. So the maximum moves = maximum pairs. So indeed answer is maximum number of disjoint matching pairs.
Thus problem reduces to computing the maximum number of matching pairs of '(' and ')' and '[' and ']' that can be formed from the string, with the condition that each opening must appear before its closing (since subsequence respects order) and characters not reused. This is exactly the count we described.
Hence solution: For each test case, scan s, maintain two counters open_round and open_square. For char c:
if c == '(' -> open_round++;
if c == ')' -> if open_round>0 then open_round--, ans++;
if c == '[' -> open_square++;
if c == ']' -> if open_square>0 then open_square--, ans++;
That's O(n) per test case, total O(total length).
But let's confirm with some tricky cases: "((()))". Greedy: all three pairs => ans=3. Can we do 3 moves? Yes: take outer pair (1,6) as "()", then middle (2,5) as "()", then inner (3,4) as "()". Works.
Now consider "(()())". Greedy: on scanning: '(' open1; '(' open2; ')' -> ans1, open=1; '(' open2; ')' -> ans2, open=1; ')' -> ans3, open=0. So 3 pairs. Works.
Now consider "([()])". This is RBS. Greedy: '(' open1=1; '[' open2=1; '(' open1=2; ')' -> ans1 (parentheses), open1=1; ']' -> ans2 (square), open2=0; ')' -> ans3 (parentheses), open1=0. So 3 pairs. Could we get more? There are 6 characters, max 3 moves. So yes.
Now consider a case where there are many brackets but the greedy per type might not be optimal due to interaction? Example: "([)]" we already did. Greedy gave 2. That's max.
Thus solution stands.
But hold on: there is nuance: In the definition of RBS, concatenation is allowed. So "()[]" is an RBS. Our approach would count two moves (each pair). Could we instead get 3 moves by splitting "()[]" into three moves? No, because only 4 characters.
Now consider a more complex scenario: Suppose we have "(([]))". This is 6 chars: '(' '(' '[' ']' ')' ')'. Greedy: '(' open1=1; '(' open1=2; '[' open2=1; ']' -> ans1 (square), open2=0; ')' -> ans2 (parentheses), open1=1; ')' -> ans3, open1=0. So 3 pairs. That's max.
Now, could there be a scenario where a pair of same type cannot be formed because there is an unmatched bracket of the other type interfering in the greedy? No, because we treat each type independently. But is it always valid to match a '(' with any later ')' regardless of what's in between? Yes, because we can skip all intermediate characters. So the greedy per type works.
Thus answer is straightforward.
Let's check limits: total length ≤ 2e5, t ≤ 1000. O(total length) is fine.
Now, I recall there is a Codeforces problem: "1472B" no. Actually, this seems like Codeforces Round #1462 problem "Regular Bracket Sequence" but with two types? Wait there is a problem "Regular Bracket Sequence" with one type, but this is with two types and moves. I recall a problem: "1462A" not. Might be from Codeforces Round #1462, actually problem "1462C" is something else. Let me think: The sample matches problem "137B" no. Actually, I recall a problem: "1494A" maybe? There's a problem "1452C - Two Brackets"? That problem asks: given a string, maximum number of brackets you can remove by deleting a regular bracket subsequence each move? Actually, I recall a Codeforces problem: "C. Two Brackets" from Round #1452? I'm not sure. But there is a known problem: "C. Bracket Sequence" or "C. Remove the Subsequence" but this one specifically: "Maximum number of moves" where each move you can remove a regular bracket subsequence. The solution is indeed to count matched pairs of '(' and ')' and '[' and ']' separately. I think it's Codeforces problem 1462C? Let's search memory: I think it's from Codeforces Round #1462 (Div. 1+2) problem "C. Bracket Sequence" maybe? Actually, there is a problem "C. Bracket Sequence" from Round #1462 that involves two types? I'm not certain. But I've seen a problem: "C. Bracket Sequence" where you have to find maximum number of operations to remove regular bracket sequences. And the solution is exactly that.
Thus, answer is simple.
Now we need to implement for t test cases.
One more check: The string may be long, but scanning is fine.
Now, let's ensure there is no hidden trap: Could there be a scenario where using a longer RBS allows us to use characters that would otherwise be unusable in any pair, thereby increasing the total number of moves beyond the simple pair count? For instance, suppose we have an opening '(' and a closing ')' but they are in the wrong order relative to each other? That can't happen because one must be before the other. But if there is an opening '(' and a closing ')' but there is an intervening unmatched '[' that somehow prevents pairing? No, we can skip it.
What about a scenario where we have "([)]" we already did. Good.
Consider: ")[()]". s = ')','(','[',']',')'? Actually ")[()]" is 5 chars: 1=')',2='(',3='[',4=']',5=')'. Greedy: ')' open1=0; '(' open1=1; '[' open2=1; ']' -> ans1 (square) => ans=1, open2=0; ')' -> open1>0 => ans=2, open1=0. So ans=2. Can we get 2 moves? Possibly: Remove "()" from positions 2 and 5? But check: positions 2='(',5=')' -> "()" is RBS. After removal, remaining: positions 1,3,4 -> ')', '[', ']' -> that's ")] ]"? Actually string: 1=')',3='[',4=']' => ")[]". Can we extract an RBS from this? Possibly "[]" from positions 3,4 -> "[]". That's second move. So 2 moves. Works.
What about removing "[]" first then "()"? That would be positions 3,4 -> "[]", remaining: 1,2,5 -> ')','(',')' -> that's ")()". Can we extract an RBS? Yes, "()" from positions 2,5? Wait after removal of 3,4, the string is indices 1,2,5: characters: ')','(',')'. In this string, we can take subsequence (2,5) -> "()". So also 2 moves. So fine.
Thus solution holds.
Edge Cases: t up to 1000, total length up to 2e5. Use fast I/O.
Implementation: For each test case, read string s (maybe with spaces? no). Compute ans as described.
But wait: The problem statement: "In one move you can choose a non-empty subsequence of the string s (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order." This is exactly what we used.
Thus answer: sum of matched pairs.
Now I'll produce final answer explanation and code.
But to be thorough, we could also think about a potential nuance: The subsequence chosen must be non-empty and RBS. Could we remove an RBS that is not a concatenation of pairs but something like "([)]"? Actually, "([)]" is not an RBS. So no.
Thus, final.
I'll implement solve().
Pseudo:
def solve():
import sys
data = sys.stdin.read().split()
t = int(data[0])
out = []
idx = 1
for _ in range(t):
s = data[idx]; idx+=1
open1 = 0
open2 = 0
ans = 0
for ch in s:
if ch == '(':
open1 += 1
elif ch == ')':
if open1 > 0:
open1 -= 1
ans += 1
elif ch == '[':
open2 += 1
elif ch == ']':
if open2 > 0:
open2 -= 1
ans += 1
out.append(str(ans))
sys.stdout.write("\n".join(out))
This is O(total length). Works.
Now, just to be absolutely sure, I'll test some random strings with brute force for small lengths to verify this algorithm yields the maximum moves. Since n small, we could brute force all possible sequences of moves? But that's complex. However, we can think of it as: the answer is the maximum number of disjoint pairs we can match. And we have argued it's an upper bound and achievable. Let's prove more formally:
Let M be the maximum number of moves. Let total removed characters be R. Since each move removes an RBS, which has even length at least 2, we have R >= 2M. Also, in each RBS, we can pair each opening with its matching closing (in that RBS). This gives a set of disjoint pairs (opening, closing) from the original string (because the RBS's are disjoint). So M ≤ number of disjoint pairs we can select (matching same type, opening before closing). Conversely, we can achieve the number of such pairs as moves by removing each pair individually. Therefore, M equals the maximum number of disjoint matching pairs. So it's correct.
Thus final solution.
But wait: In the above argument, we said each RBS can be decomposed into matching pairs. However, are these pairs necessarily disjoint? Yes, within an RBS, the standard pairing of brackets gives a set of disjoint pairs. And across moves, the sets are disjoint. So overall we have a collection of disjoint pairs from the original string. So the total number of moves is at most the total number of such pairs. However, we need to ensure that the pairs we get from decomposing RBS's are indeed valid pairs (i.e., opening before closing) in the original order. They are, because the RBS itself is a subsequence, and the pairing within the RBS respects the order of that subsequence, which is a subsequence of the original. But does the pairing guarantee that the opening appears before the closing in the original string? Yes, because the subsequence preserves order. So each pair (i,j) from the decomposition has i<j in original indices. Also, they are of same type. So they are valid pairs in our sense.
Thus M ≤ maximum number of such pairs.
Now, is it always possible to achieve exactly the maximum number of pairs? The greedy algorithm gives the maximum number of pairs, and we can schedule them as moves. But does there exist a set of disjoint pairs achieving that maximum that can be removed as separate moves? Yes, as argued, any set of disjoint pairs can be removed one by one: just remove each pair as a move, because each pair is an RBS. But we must ensure that when removing a pair, the two characters are still present and we can select them as a subsequence from the current string. That is always possible if they haven't been removed yet. Since pairs are disjoint, at the time we remove a pair, both characters are present. Also, there might be other characters between them, but we can select them as a subsequence by skipping those. So yes.
Thus the answer is exactly maximum number of pairs.
Hence code.
Now we should consider if there is any scenario where using a longer RBS could produce more than the maximum pairs? Not possible as argued.
Thus final answer.
Now write solution explanation and code.
But as a final check, let's examine the sample provided: matches.
Thus done.
Now produce final answer. The problem reduces to counting the maximum number of disjoint matching pairs of the same bracket type: '(' with ')' and '[' with ']'.
Each such pair is itself a regular bracket sequence, so it can be removed in one move.
Conversely, any move removes at least one such pair, so the total number of moves cannot exceed the number of pairs we can form.
Therefore, the answer is simply the sum of the number of matched parentheses and the number of matched square brackets, which can be computed with a single scan using two counters.
import sys
def solve() -> None:
data = sys.stdin.read().split()
t = int(data[0])
out = []
idx = 1
for _ in range(t):
s = data[idx]
idx += 1
open_round = 0
open_square = 0
ans = 0
for ch in s:
if ch == '(':
open_round += 1
elif ch == ')':
if open_round:
open_round -= 1
ans += 1
elif ch == '[':
open_square += 1
elif ch == ']':
if open_square:
open_square -= 1
ans += 1
out.append(str(ans))
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
solve()