using System; using System.Collections.Generic; using System.Text; public class brackets { public static void Main(string[] args) { int n = Int32.Parse(Console.ReadLine()); for(int i = 0; i < n; i++) Console.WriteLine(new Solver(Console.ReadLine()).Solve()); } private class Solver { private string[] s; private int [] r; public Solver(string str) { s = str.Replace("a list of", "lst").Replace(",", "").Split(' '); r = new int[s.Length]; for(int i = 0; i < r.Length; i++) { r[i] = i; } } public string Solve() { int n = s.Length; while(--n > 0 && s[n] != "and") ; bool flag = false; Stack stack = new Stack(); stack.Push(0); for(int i = 1; i < n; i++) { switch(s[i]) { case "lst": stack.Push(i); flag = flag || (stack.Count >= 2 && s[i-1] == "and"); break; case "and": r[stack.Pop()] = i; flag = (stack.Count >= 2); // overwrite break; } } int[] w = stack.ToArray(); Array.Reverse(w); flag = flag || (w.Length >= 2 && w[1] - w[0] == 1); r[w[0]] = n; int idx = 0; return flag ? "AMBIGUOUS" : Build(ref idx); } private string Build(ref int idx) { string res = ""; int end = r[idx] + 1; while(++idx <= end) { switch(s[idx]) { case "lst": res += " " + Build(ref idx); --idx; break; case "and": break; default: res += " " + s[idx]; break; } } return "(" + res.Substring(1) + ")"; } } }