import java.io.*; import java.util.*; public class bracket_yuizumi { public static void main(String[] args) throws Exception { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); for(int i = 0; i < n; i++) { System.out.println(new Parser(br.readLine()).parse()); } } finally { if(br != null) { br.close(); } } } // S -> L S (L == lst) // S -> L T // S -> L X // X -> S X // X -> T X // X -> S Y // X -> T Y // Y -> A S (A == and) // Y -> A T private static class Parser { private static final int S = 0; private static final int X = 1; private static final int Y = 2; private static final int T = 3; private static final int L = 4; private static final int A = 5; private String[] s; private int n; private int[][][] cyk; public Parser(String str) { str = str.replaceAll("a list of", "lst"); s = str.split(",? "); n = s.length; } private void update(int i, int j, int l, int lhs, int rhs1, int rhs2) { if(cyk[i][j][rhs1] == 0 || cyk[i+j][l-j][rhs2] == 0) return; else if(cyk[i][j][rhs1] == -1 || cyk[i+j][l-j][rhs2] == -1) cyk[i][l][lhs] = -1; else if(cyk[i][l][lhs] != 0) cyk[i][l][lhs] = -1; else cyk[i][l][lhs] = (j << 8) | (rhs1 << 4) | rhs2; } private void build(StringBuffer sb, int i, int l, int sym) { int j = cyk[i][l][sym] >> 8; int rhs1 = (cyk[i][l][sym] >> 4) & 15; int rhs2 = (cyk[i][l][sym] >> 0) & 15; switch(sym) { case S: sb.append('('); build(sb, i + j, l - j, rhs2); sb.append(')'); break; case X: build(sb, i, j, rhs1); sb.append(' '); build(sb, i + j, l - j, rhs2); break; case Y: build(sb, i + j, l - j, rhs2); break; case T: sb.append(s[i]); break; } } public String parse() { cyk = new int[n][n+1][6]; for(int i = 0; i < n; i++) { for(int j = 0; j <= n; j++) { Arrays.fill(cyk[i][j], 0); } } for(int i = 0; i < n; i++) { if(s[i].equals("lst")) cyk[i][1][L] = 1; else if(s[i].equals("and")) cyk[i][1][A] = 1; else cyk[i][1][T] = 1; } for(int l = 2; l <= n; l++) { for(int i = 0; i <= n - l; i++) { for(int j = 1; j <= l - 1; j++) { update(i, j, l, S, L, S); update(i, j, l, S, L, T); update(i, j, l, S, L, X); update(i, j, l, X, S, X); update(i, j, l, X, T, X); update(i, j, l, X, S, Y); update(i, j, l, X, T, Y); update(i, j, l, Y, A, S); update(i, j, l, Y, A, T); } } } if(cyk[0][n][S] == -1) { return "AMBIGUOUS"; } StringBuffer sb = new StringBuffer(); build(sb, 0, n, S); return sb.toString(); } } }