* 6.3 Tree and two fork tree
* * Ball Drop problem
//Ball Drop problem/*There is a binary tree with a maximum depth of D, and all leaves have the same depth. All nodes are numbered 1,2,3,4,..., 2^d-1 from top to bottom. Place a small ball at node 1 and it will fall. Each inner node has a switch, initially all closed, when there is a small ball falling on the switch is, the state will change. 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. Some small balls begin to fall from Node 1, and where does the last ball fall? Input: Leaf depth D and ball number I output: The number of the last leaf of the first ball*/#include<cstdio>#include<cstring>Const intMaxd = -;ints[1<<maxd];//the maximum number of nodes is 2^maxd-1.intMain () {intD, I; while(SCANF ("%d%d", &d, &i) = =2) {memset (s),0,sizeof(s));//Switch intK, n = (1<<D)-1;//n is the maximum node number. for(inti =0; i < I; i++) {//continuously let i a ball dropK =1; for(;;) {S[k]= !S[k]; K= s[k]?k*2: k*2+1;//Select the drop direction according to the switch if(k > N) Break;//It's out of bounds.}} printf ("%d\n", k/2);//number before out of bounds } return 0; }
Operation Result:
Algorithmic Competition Primer Classic _6 Data structure basics