# C ++ beginners record (tree and binary tree)

Binary numbering
examples 6-6 the fate of the ball
has a binary tree, the maximum depth is D, and all the leaves have the same depth. All the nodes from top to bottom, left to right are numbered 1,2,3,4, ...., 2 ^ D- 1. At node 1 placed ball, he will go whereabouts. Each node has a switch on, all the initial closed whenever there is a switch when the ball falls, the state will change, when a ball reaches the node, if the switch is turned off on the node to go left, or right away, he walked up to the leaf node, small ball starting at node 1 in turn fall. Finally, where a small ball back to it? Enter leaves the depth D, the number of balls I, leaf number input I of balls last located. Suppose I does not exceed the number of leaves of whole tree, D <= 20. Up to 1000 sets of data input.
GET
. 4 2
. 3. 4
10. 1
2 2
. 8 128
16 12345
PUT
12 is
. 7
512
. 3
255
36358

#include<iostream>
#include<cstring>
const int maxd=20;
int s[1<<maxd];
int main()
{
    int D,I;
    while((cin>>D>>I)==2)
    {
        memset(s,0,sizeof(s));
        int k=1,n=(1<<D)-1;
        for(int i=0;i<I;i++)
        {
            k=1;
            for(;;;)
            {
                s[k]=!s[k];
                k=s[k]?2*k:2*k+1;
                if(k>n)break;
            }
        }
        cout<<k/2<<endl;
    }
    return 0;
}

Very difficult to understand the basis of the code, with k now represents the node where the position of the ball then determines whether the cycle after the next step boundary is out of bounds and out of the cycle of k is initialized, i.e., until the end of the cycle I, balls fall in the end.

Guess you like

Origin www.cnblogs.com/xiaofengqaq/p/11242318.html
Recommended