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
import java.util.Scanner;

/**
 * Created by stawicad on 2016-11-15.
 */
public class slo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(word(sc.nextInt(), sc.nextLong()));
    }

    private static String word(final int n, long k) {
        final int[][] states = {
                {1, 2},
                {0, 2},
                {0, 1},
                {0, 1, 2}
        };
        long last = 3;
        StringBuilder answer = new StringBuilder();
        char prev = 'd';
        for (int i = 1; i < n & k > 0; i++) {
            if(k == k % (last / 3)) {
                answer.append(prev = character(prev, --k, last, states));
            }
            else {
                last = last * 2 + 3;
            }
        }
        if(last < k) return "NIE";
        while (k > 0) {
            answer.append(prev = character(prev, --k, last, states));
            k = k % (last / 3);
            last = (last - 3) / 2;
        }
        return answer.toString();
    }

    private static char character(final int prev, final long k, final long last, final int[][] states) {
        return (char) ('a' + states[prev - 'a'][(int) (k / (last / 3))]);
    }
}