#P9446. Ancient Parentheses Reordering

    ID: 22598 Type: Default 1000ms 256MiB

Ancient Parentheses Reordering

Ancient Parentheses Reordering

Archaeologists have uncovered mysterious clay tablets in the depths of Alutila Cave. The inscriptions include two symbols that resemble opening and closing parentheses, suggesting that these tablets might encode a structured work, such as a program, an epic, or even tax records! However, the tablets lie in disarray. Your task is to rearrange the tablets into a sequence such that the parentheses form a properly nested structure.

A properly nested structure (considering only the parentheses) is defined recursively as follows:

  • $()$
  • $(A)$, where $A$ is a properly nested structure
  • $AB$, where both $A$ and $B$ are properly nested structures

Given a string consisting solely of the characters '(' and ')', rearrange the characters to form a properly nested parentheses sequence if possible. If no valid arrangement exists, output impossible.

inputFormat

The input is a single line containing a non-empty string made up of the characters '(' and ')'. This string represents the unordered tablets found in the cave.

outputFormat

Output a properly nested parentheses sequence that can be obtained by rearranging the characters. If no such rearrangement is possible, output the string impossible.

sample

())(
(())