Almost correct bracket sequence

3.9

15 votes
Applications of Dynamic Programming, Algorithms, Dynamic Programming, Dynamic programming
Problem

The correct bracket sequence (also known as a balanced bracket sequence or correct parenthesis sequence) is a string consisting of only brackets ("(" and ")") such that this sequence when inserted certain numbers and mathematical operations give a valid mathematical expression. For instance, (())() is a correct bracket sequence and 1+(2(34)/6)+(78) is one of the possible expressions that can be obtained from it but ()) is not a correct bracket sequence. An empty string is a correct bracket sequence as well.

An almost correct bracket sequence is a string that consists of only brackets that can be turned into a correct bracket sequence by removing exactly one bracket from it. For instance, ()) is an almost correct bracket sequence because removing any of closing brackets turns it into a correct bracket sequence () but ((( is not an almost correct bracket sequence. Obviously, the length of each almost correct bracket sequence is an odd number.

You are given two integers n and k. Consider all almost correct bracket sequences of length n and order these sequences lexicographically assuming that ( < )). Determine the kth sequence in the ordering sequence or report that the number of almost correct bracket sequences of length n is less than k.

Input format

  • First line: T denoting the number of test cases
  • Next T lines: Two integers n and k the length of the required almost correct bracket sequence and its position in lexicographic order

Output format

For each test case, print the answer in a separate line. If there are less than k almost correct bracket sequences of length n, then print Impossible. Otherwise, print the required sequence.

Constraints

1T5000

1n65n is odd

1k2631

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

There are only two almost correct bracket sequences of length 1: "(" and ")" (both turn into empty string after removing a bracket), "(" comes first in lexicographic order.

The first two almost correct bracket sequences of length 3 in lexicographic order are "(()" and "()(".

Editor Image

?