2609. Bracket Expression
Constraints
Time Limit: 1 secs, Memory Limit: 256 MB
Description
A string S that consists of bracket (), [] and {} only is considered to be valid:
(a). if S is an empty string;
(b). if both A and B are valid, and S = AB;
(c). if A is valid, and S = (A);
(d). if A is valid, and S = [A];
(e). if A is valid, and S = {A};
Given the length n, we can construct many valid bracket strings. For example, suppose n = 4, then there are 18 valid bracket strings, which are listed in alphabetical order as follows: (()), ()(), ()[], (){}, ([]), ({}), [()], [[]], [](), [][], []{}, [{}], {()}, {[]}, {{}}, {}(), {}[], {}{}.
If we numbered them with integers starting from 0, then string ()[] can be called the 2nd valid bracket string of length 4, and the 14th string is {{}}.
Now, given the length n, and the index k, your task is to find out which the corresponding valid bracket string is in alphabetical order.
Input
Input may contain several test cases. The first line is a positive integer, T (T<=100), the number of test cases below. Each test case contains two integers n, k in a single line, n (1<=n<=32, n is even) is the length of bracket string, and k (0<=k<=10^18) is the index of the valid bracket string that should be found.
Output
For each test case, if the k-th valid string of length n in alphabetical order exists, just output that string, otherwise, output “invalid” (without quotation mark).
Sample Input
3 2 3 4 2 4 14
Sample Output
invalid ()[] {{}}
Problem Source
系列热身赛2@2011年上半学期算法考试和4+2选拔赛'
// Problem#: 2609
// Submission#: 3593218
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <stdio.h>
#include <string.h>
const int MAXN = 20;
long long f[MAXN][MAXN];
long long Index;
int n;
char * str = "()[]{}";
char stack[MAXN * 2];
void init() {
int i, j;
memset(f, 0, sizeof(f));
f[0][0] = 1;
for (j = 1; j < MAXN; j++) f[0][j] += f[0][j - 1];
for (i = 1; i < MAXN; i++) {
for (j = 0; j < MAXN; j++) {
if (j + 1 < MAXN) f[i][j] += 3 * f[i - 1][j + 1];
if (j > 0) f[i][j] += f[i][j - 1];
}
}
}
void show(int pos, int depth, int m, long long Index) {
if (pos == n) return;
int i;
for (i = 0; i < 6; i++) {
if (i % 2 == 0 && m >= 1) {
if (Index < f[m - 1][depth + 1]) break;
Index -= f[m - 1][depth + 1];
} else if (depth >= 1 && str[i] == stack[depth - 1]) {
if (Index < f[m][depth - 1]) break;
Index -= f[m][depth - 1];
}
}
printf("%c", str[i]);
if (i % 2 == 0) {
stack[depth] = str[i + 1];
show(pos + 1, depth + 1, m - 1, Index);
} else show(pos + 1, depth - 1, m, Index);
}
int main() {
init();
int tn;
scanf("%d", &tn);
while (tn--) {
scanf("%d%lld", &n, &Index);
if (Index >= f[n / 2][0]) printf("invalid");
else show(0, 0, n / 2, Index);
printf("\n");
}
return 0;
}