A subset in a sequence

3.9

95 votes
Basic Programming, Bit Manipulation
Problem

You are given a set S consisting of non-negative powers of three S={1, 3, 9, 27, ...}. Consider the sequence of all non-empty subsets of S ordered by the value of the sum of their elements. You are also given a single element n. You are required to find the subset at the nth position in the sequence and print it in increasing order of its elements.

Input format

  • The first line contains one integer q denoting the number of queries. t test cases follow.
  • The first line of each test case consists of a single integer n.

Output format

  • In the first line, print the size of the nth subset.
  • In the next line, print the elements of the nth subset in increasing order separated by space.

Constraints

1t1051n1012

Sample Input
5
1
6
11
9
19

Sample Output
1
1 
2
3 9 
3
1 3 27 
2
1 27 
3
1 3 81 

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

In the first test case, of the example n = 1 and if we write all the subsets in increasing order of the sum of their elements the set {1} comes at the 1st position.

In the second test case, the set {3,9} comes at the 6th position.

In the third test case, the set {1,3,27} comes at the 11th position.

Editor Image

?