For the complete binary tree of depth k, answer q queries each summing m elements of its Prüfer code at positions a, a+d, ..., a+(m-1)d.
Hard8MathTreeDivide and conquerImplementationNo attempts yetTime limit7sMemory limit512 MBA tree is a graph with n nodes and n−1 undirected edges in which every pair of nodes is joined by exactly one path. In a labeled tree, each node is labeled with a different integer between 1 and n.
The Prüfer code of a labeled tree is the sequence built by removing nodes one at a time until only two nodes are left. In each step, remove the leaf with the smallest label and append the label of its only neighbour to the end of the code. A leaf is a node with exactly one neighbour. The Prüfer code of a labeled tree is therefore an integer sequence of length n−2, and the original tree can be reconstructed from it.
The complete binary tree of depth k, written Ck, is the labeled tree on 2k−1 nodes in which node j is joined to nodes 2j and 2j+1 for every j<2k−1. Write the Prüfer code of Ck as p1,p2,…,p2k−3.
The Prüfer code of Ck can be very long, so you do not print it. Instead, answer q questions about sums of selected elements of the code. Each question consists of three integers a, d and m, and its answer is pa+pa+d+pa+2d+⋯+pa+(m−1)d.
The first line contains two integers k and q (2≤k≤30, 1≤q≤300): the depth of the complete binary tree and the number of questions. Each of the next q lines contains one question as three positive integers aj, dj and mj, where aj, dj and aj+(mj−1)dj are all at most 2k−3.
Print q lines. Line j contains a single integer, the answer to the j-th question.

When the Prüfer code of C3 is built, the nodes are removed in the order 4, 5, 2, 1, 6. The Prüfer code of C3 is therefore 2, 2, 1, 3, 3.