This page is still under construction.

Parts of this page are still being built. What you see may change.

Cumulative Code

Time limit7sMemory limit512 MB

Summary
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.
Level

Hard8 of 10

Topics
Math, Tree, Divide and conquer, Implementation
Solved
No attempts yet

Problem

A tree is a graph with nn nodes and n−1n-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 11 and nn.

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−2n-2, and the original tree can be reconstructed from it.

The complete binary tree of depth kk, written CkC_k, is the labeled tree on 2k−12^k - 1 nodes in which node jj is joined to nodes 2j2j and 2j+12j+1 for every j<2k−1j < 2^{k-1}. Write the Prüfer code of CkC_k as p1,p2,…,p2k−3p_1, p_2, \ldots, p_{2^k-3}.

The Prüfer code of CkC_k can be very long, so you do not print it. Instead, answer qq questions about sums of selected elements of the code. Each question consists of three integers aa, dd and mm, and its answer is pa+pa+d+pa+2d+⋯+pa+(m−1)dp_a + p_{a+d} + p_{a+2d} + \cdots + p_{a+(m-1)d}.

Input

The first line contains two integers kk and qq (2≤k≤302 \le k \le 30, 1≤q≤3001 \le q \le 300): the depth of the complete binary tree and the number of questions. Each of the next qq lines contains one question as three positive integers aja_j, djd_j and mjm_j, where aja_j, djd_j and aj+(mj−1)dja_j + (m_j - 1)d_j are all at most 2k−32^k - 3.

Output

Print qq lines. Line jj contains a single integer, the answer to the jj-th question.

Hint

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

Examples3

  1. Example 1

    Input
    3 5
    1 1 1
    2 1 1
    3 1 1
    4 1 1
    5 1 1
    
    Expected output
    2
    2
    1
    3
    3
    
  2. Example 2

    Input
    4 4
    2 1 5
    4 4 3
    4 8 1
    10 3 2
    
    Expected output
    18
    15
    5
    13
    
  3. Example 3

    Input
    7 1
    1 1 125
    
    Expected output
    4031