1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class slo {

    public long position;

    public long maxLength;

    public StringBuilder sb = new StringBuilder();

    public Map<Character, Character[]> valuesMap = new HashMap<>();

    {
        valuesMap.put('a', new Character[]{'b', 'c'});
        valuesMap.put('b', new Character[]{'a', 'c'});
        valuesMap.put('c', new Character[]{'a', 'b'});
    }

    public Character lastChar;

    public static void main(String[] args) {
        slo app = new slo();
        app.readInput();
        app.process();
        app.writeOutput();
    }

    private void writeOutput() {
        System.out.println(sb);
    }

    private void process() {

        char processedTreeFirstChar = 'a' - 1;

        for (int i = 0; i < 3; i++) {
            double pos = getLog(position + 1L);

            processedTreeFirstChar++;
            if (pos <= maxLength) {
                sb.append(processedTreeFirstChar);
                lastChar = processedTreeFirstChar;
                break;
            }
            position -= (1L << maxLength) - 1;
        }

        if (lastChar == null) {
            sb.append("NIE");
            return;
        }

        processTree(position, maxLength);
    }

    private double getLog(long number) {
        long highestBit = Long.highestOneBit(number);
        return Long.numberOfTrailingZeros(highestBit) + (highestBit == number ? 0 : 0.5);
    }

    private void processTree(long positionInATree, long treeSize) {
        for (long i = 1; i < treeSize; i++) {

            if (positionInATree == 1)   // ten wierzcholek juz zostal dodany
                return;

            positionInATree -= 1;       //wyrzucamy korzen
            int branch = 0;
            double log = getLog(positionInATree + 1L);
            if (treeSize - i < log) {
                branch = 1;
                positionInATree -= (1L << (treeSize - i)) - 1;
            }
            sb.append(lastChar = valuesMap.get(lastChar)[branch]);
        }
    }

    private void readInput() {
        Scanner in = new Scanner(System.in);
        maxLength = in.nextLong();
        position = in.nextLong();
    }
}