C + + two fork Tree

Source: Internet
Author: User

/*
Problem: Small ball Drop: There is a binary tree with a maximum depth of D, and all leaves have the same depth. All nodes are numbered from top to bottom, from left to right, all the way to 2^d-1. Place a small ball at node 1 where it will fall,
Each node has a switch, the initial state is all closed, and each time a ball falls on a switch, the state changes. When the ball reaches an inner node, if the switch on the node is closed, go left, or go to the right,
Until you go to the leaf node.
Enter the leaf depth and the number of balls, and output the last leaf node number of the first ball
Solution: For a node, its left child and right child nodes are 2k and 2k+1 respectively.

*/


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace Std;
const int MAXD=20;
int s[1<<maxd];//Maximum number of nodes is 2^maxd-1
int main ()
{
int d,i;
while (scanf ("%d%d", &d,&i) ==2) {
Memset (s,0,sizeof (s));//Switch
int k,n= (1&LT;&LT;D) -1;//n is the maximum node number
for (int i=0;i<i;i++) {//Let I drop a ball continuously
k=1;
for (;;) {
s[k]=!s[k];//the side switch status
k=s[k]?k*2:k*2-1;//three-mesh operator assignment
if (k>n) break;//has fallen "out of Bounds"
}
}
printf ("%d\n", K/2);//leaf number before bounds
}

return 0;
}

C + + two fork Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.