/* Sample solution to "Necklace Decomposition" from NCPC 2005 * Algorithm: memoization, exploit fact that decomposition is unique. * Author: Per Austrin */ #include #include #include using namespace std; bool less(char *b1, int l1, char *b2, int l2) { int r = strncmp(b1, b2, min(l1, l2)); if (r) return r < 0; return l2 > l1; } int isneck[150][150]; int begin[150]; char str[150], nstr[300]; bool IsNeck(int begin, int end) { int &r = isneck[begin][end], n = end-begin; if (r == -1) { strncpy(nstr, str+begin, n); strncpy(nstr+n, str+begin, n); r = true; for (int i = 1; r && i < n; ++i) if (less(nstr+i, n, str+begin, n)) r = false; } return r; } int Begin(int end) { int &r = begin[end]; if (r == -1) for (r = end; r--; ) if (IsNeck(r, end) && (r == 0 || (less(str+r, end-r, str+Begin(r), r-Begin(r)) && !IsNeck(Begin(r), end)))) break; assert(r != -1); return r; } int main(void) { int n; for (scanf("%d", &n); scanf("%s", str), n--; ) { bool insert[200]; int b = strlen(str); memset(begin, -1, sizeof(begin)); memset(isneck, -1, sizeof(isneck)); memset(insert, false, sizeof(insert)); while (Begin(b)) insert[b = Begin(b)] = true; printf("("); for (int i = 0; str[i]; ++i) { if (insert[i]) printf(")("); printf("%c", str[i]); } printf(")\n"); } return 0; }