Ratio

4.5

28 votes
Adhoc, Basic Programming, Basics of Implementation, Implementation, Medium
Problem

There are 2 types of chocolates in Chocoland denoted by A and B.

The cholates are lined up in a queue.You want to satisfy your friends by distributing some number of non-empty contiguous chocolates such that the ratio of number of type A chocolates to number of type B chocolates is same for all the friends.You have to distribute all the chocolates and satisfy maximum number of friends.
Therefore you have to find the maximum number of friends that can be satisfied.

Input Format

The first line of input contains the number of test cases T .
Each test case starts with one line containing an integer N which is the length of the description of a queue.

Each of the following lines consists of an integer and one of the characters A or B, meaning that characters of the given type (A or B) follow next in the queue.

Output Format

For each test case, output a single line containing the maximum number of friends that can be satisfied.

Constraints

1T50

1N105

1K109

Length of queue 109

Sample Input
2
3 
1 A
3 B 
2 A 
2 
2 B 
3 B
Sample Output
2
5
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For 1st Test Case:
Queue is ABBBAA
Distributions are AB, BBAA (Ratio 1:1)
For 2nd Test Case:
Queue is BBBBB
Distributions are B, B, B, B, B (Ratio 0:1)

Editor Image

?