/* Sample solution to Necklace * Author: Mikael Goldmann * * Checks input (does not check for garbage after last case) * No leading or trailing blanks allowed for any case. * * Problem solved by necklace() and isNecklace(). * Observe (or guess) that we should always choose the longest prefix * that is a necklace to be the first in the decomposition. * Decompose remaning suffix recursively. */ import java.io.*; class necklace_mg { static BufferedReader stdin; static PrintStream stdout; public static void main(String[] a) { Reader rdr = new InputStreamReader(System.in); stdin = new BufferedReader(rdr); OutputStream os = new BufferedOutputStream(System.out); stdout = new PrintStream(os); (new necklace_mg()).run(); stdout.close(); } void run() { int i = 0, n = 0; String s = ""; try { i = 0; s = stdin.readLine(); n = Integer.parseInt(s); for (i = 1; i <= n; ++i) solve(stdin.readLine(), i); } catch (NumberFormatException e) { System.err.println("Number of cases (" + s + ") is not an integer " + "(or contains blanks)"); } catch (IOException e) { if (i == 0) System.err.println("Cannot read number of cases"); else System.err.println("Cannot read case " + i); } } void solve(String s, int num) { /* start input validity check */ if (s == null) { System.err.println("Case " + num + ": null string"); return; } int n = s.length(); if (n == 0) { System.err.println("Case " + num + ": empty string"); return; } for (int i = 0; i < n; ++i) if (s.charAt(i) != '0' && s.charAt(i) != '1') { System.out.println("Case " + num + ": illegal character (" + s.charAt(i) + ") at index" + i); return; } /* end check */ necklace(s); } void necklace(String s) { int n = s.length(); if (n == 0) stdout.println(); else { while (!isNecklace(s.substring(0, n))) --n; stdout.print("(" + s.substring(0,n) + ")"); necklace(s.substring(n)); } } boolean isNecklace(String s) { String p = s+s; int n = s.length(); for (int k = 1; k < n; ++k){ for (int i = 0; i < n; ++i) { if (p.charAt(i) < p.charAt(i+k)) break; else if (p.charAt(i) > p.charAt(i+k)) return false; } } return true; } }