using System; using static System.Console; using System.Linq; using System.Collections.Generic; class Program { static int NN => int.Parse(ReadLine()); static int[] NList => ReadLine().Split().Select(int.Parse).ToArray(); public static void Main() { Solve(); // Test(); } static void Test() { var r = new Random(); var count = 0; while (true) { var n = 8; var c = new char[n]; for (var i = 0; i < n; ++i) c[i] = (char)(r.Next(2) + 'A'); var s = string.Concat(c); // 愚直解 var s1 = All(s); // 作成解 var s2 = Del(s); if (s1 != s2) { WriteLine(n); WriteLine(s); WriteLine(s1); WriteLine(s2); return; } ++count; if (count % 1000 == 0) WriteLine(count); } } static string All(string s) { var bcnt = s.Count(c => c == 'B'); var bitmax = (int)Math.Pow(bcnt, bcnt); var set = new HashSet(); set.Add(s); for (var b = 0; b < bitmax; ++b) { var tmp = b; var si = s.ToList(); for (var i = 0; i < bcnt; ++i) { var cnt = 0; for (var j = 0; j + 1 < si.Count; ++j) { if (si[j] == 'A') { ++cnt; if (tmp % bcnt == cnt && si[j + 1] == 'B') { si = si.Take(j).Concat(si.Skip(j + 2)).ToList(); break; } } } tmp /= bcnt; } set.Add(string.Concat(si)); } var ans = new List(set); ans.Sort(); return ans[^1]; } static void Solve() { var t = NN; var ans = new string[t]; for (var u = 0; u < t; ++u) { ReadLine(); var s = ReadLine(); ans[u] = Del(s); } WriteLine(string.Join("\n", ans)); } static string Del(string s) { var stack = new List<(int ac, int bc)>(); var tac = 0; var tbc = 0; for (var i = 0; i < s.Length; ++i) { if (s[i] == 'B' && i + 1 < s.Length && s[i + 1] == 'A') { ++tbc; stack.Add((tac, tbc)); tac = 0; tbc = 0; } else if (s[i] == 'A') ++tac; else ++tbc; } if (tac != 0 || tbc != 0) stack.Add((tac, tbc)); // WriteLine(string.Join(" ", stack)); var st2 = new List<(int ac, int bc)>(); tac = 0; tbc = 0; while (stack.Count > 0) { var cur = stack[^1]; stack.RemoveAt(stack.Count - 1); cur.ac += tac; cur.bc += tbc; tac = 0; tbc = 0; if (cur.ac < cur.bc) { cur.bc -= cur.ac; cur.ac = 0; } else if (cur.bc > 1) { cur.ac -= cur.bc - 1; cur.bc = 1; } if (cur.ac == 0) { tac = cur.ac; tbc = cur.bc; } else { st2.Add(cur); } } if (tac != 0 || tbc != 0) st2.Add((tac, tbc)); // WriteLine(string.Join(" ", st2)); var ans = new List(); while (st2.Count > 0) { var cur = st2[^1]; st2.RemoveAt(st2.Count - 1); for (var i = 0; i < cur.ac; ++i) ans.Add('A'); for (var i = 0; i < cur.bc; ++i) ans.Add('B'); } return string.Concat(ans); } }