Ball Drop
"The main topic"
There is a binary tree with a maximum depth of D, and so the depth of the leaves is the same. All nodes are numbered from left to right, from top to bottom, .... 2^d-1. Place a small ball at junction 1 and he will fall. Each inner node has a switch that is initially closed, and the state changes every time a ball falls to a switch. When the ball reaches an inner node, if the switch on the node is closed, go left, or go right until you reach the leaf junction. Such as
Analysis
First, each node is saved with an array of tags, a few small balls fall, the execution of several loops, each execution, usually to the point at which the tag array changes, so that it can refer to a different direction next time.
"Code Implementation"
Code Listing 1:
#include <stdio.h> #include <string.h>const int maxd=20;int s[1<<maxd]; The binary number that represents 2^maxd,1 moves the Maxd bit to the left, that is, the binary after 1 is appended with a maxd 0int main () { int d,i; while (~SCANF ("%d%d", &d,&i)) //Enter the depth of the leaf where d, and how many ball drops { memset (s,0,sizeof (s)); int k,n= (1<<D)-1; n is the maximum node number for (int i=0;i<i;i++) { k=1; Start for (;;) from the top of the heap { s[k]=!s[k]; After changing the direction of the piston k=s[k]? k*2:k*2+1; Determine which direction to go if (k>n) //out of bounds break ; } } printf ("%d\n", K/2); } return 0;}
This code is simple, but the data is too large to time out, it is suitable to understand the process of the ball falling
Code Listing 2:
#include <stdio.h> #include <string.h>int main () { int d,i; while (~SCANF ("%d%d", &d,&i)) { int k=1; for (int i=0;i<d-1;i++) //have d layer, just go through the D-time if (i%2) //I ball to each layer, only consider the first I on the line, if it is odd it will go left, if it is even he went right { k=k*2; I= (i+1)/2; } else { k=k*2+1; i/=2; } printf ("%d\n", k); } return 0;} /* Input: 4 23 410 12 28 12816 12345 output: 127512325536358*/
Binary tree: Small ball drop