[Ultraviolet A 679] Dropping bils (Ball fall), droppingbils
Description
There is a binary tree with the maximum depth of D and the depth of all leaves is the same. Numbers of all nodes from top to bottom from left to right are 1, 2, 3 ,..., 2eD-1. Place a ball at Node 1 and it will fall. Each node has a switch, which is initially closed. When a ball falls onto a switch, its status changes. When the ball reaches an internal node, if the switch is off, it goes up. Otherwise, it goes down until it reaches the leaf node, as shown in.
Input & Output
Some balls fall from node 1 in sequence. Where will the last ball fall? Enter the leaf depth D and the number of small balls I, and output the leaf number at the end of the I small ball. Assume that I cannot exceed the number of leaves of the entire tree; D <= 20. The output can contain up to 1000 groups of data.
Sample Input
4 2
3 4
10 1
2 2
8 128
16 12345
Sample Output
12
7
512
3
255
36358
# Include <cstdio> # include <cstring> # define MAX 20int s [1 <MAX]; // 1 <MAX is 2MAX, and the maximum number of nodes is 2MAX-1int main (void) {int D, I; while (scanf ("% d", & D, & I) = 2) // = 2 means: if both D and I are read, scanf returns 2 {memset (s, 0, sizeof (s); // switch, the initial value is set to 0 (disabled by default) int k, I, n = (1 <D)-1; // n is the maximum number of knots for (I = 0; I <I; I ++) // continuously drop the I ball {k = 1; for (;) {s [k] =! S [k]; // formula for changing the state. The conversion between 1 and 0 k = s [k]? K * 2: k * 2 + 1; // if (k> n) break; // out of bounds} printf ("% d \ n ", k/2); // leaf number before "exit"} return 0 ;}
Analysis
① For a node k, the numbers of its left node and right node are 2 k and 2 k + 1 respectively.
② Although each ball is strictly falling D-1 times, but the above Code using if (k> n) break method to judge "out of the world" is more general.
③ This program is too large: Since I can be as high as 2 (D-1), the total number of dropped layers of each test data may be as high as 219*19 (I * 19) = 9961472, A total of 1000 groups of data may exist.