第一种做法是直接模拟,但是会超时。
转载请注明:http://blog.csdn.net/c602273091/article/details/54233540
#include <iostream>
#include <cmath>
#include <cstring>
static void ProcessDepthDAndIthBallDrop(int Depth, int I);
//int ball_num = pow(2, Depth - 1) + 1;
int ball_tree[524288];
int main()
{
int num_test_case;
while(std::cin >> num_test_case && num_test_case != -1)
{
for(int i = 0; i < num_test_case; i++)
{
int D, I;
std::cin >> D >> I;
ProcessDepthDAndIthBallDrop(D, I);
}
}
return 0;
}
static void ProcessDepthDAndIthBallDrop(int Depth, int I)
{
std::memset(ball_tree, 0, 524288 * sizeof(int));
int output_pos = 1;
for(int i = 0; i < I; i++)
{
output_pos = 1;
for(int d = 0; d < Depth - 1; d++)
{
if(ball_tree[output_pos]) // true to the right.
{
ball_tree[output_pos] = 1 - ball_tree[output_pos];
output_pos = 2*output_pos + 1;
}
else // false to the left.
{
ball_tree[output_pos] = 1 - ball_tree[output_pos];
output_pos = 2 * output_pos;
}
}
}
std::cout << output_pos << std::endl;
}
第二种方法是把没错落下的轨迹记录下来,然后就可以发现其中的规律。
发现每经过最后一层的节点数的更新,整个图会恢复成最原始的样子。
可以得到:
#include <iostream>
#include <cmath>
#include <cstring>
static void ProcessDepthDAndIthBallDrop(int Depth, int I);
//int ball_num = pow(2, Depth - 1) + 1;
int ball_tree[524288];
int main()
{
int num_test_case;
while(std::cin >> num_test_case && num_test_case != -1)
{
for(int i = 0; i < num_test_case; i++)
{
int D, I;
std::cin >> D >> I;
int ball_num = pow(2, D - 1);
I = I%ball_num;
if (!I)
{
I = ball_num;
}
ProcessDepthDAndIthBallDrop(D, I);
}
}
return 0;
}
static void ProcessDepthDAndIthBallDrop(int Depth, int I)
{
std::memset(ball_tree, 0, 524288 * sizeof(int));
int output_pos = 1;
for(int i = 0; i < I; i++)
{
output_pos = 1;
for(int d = 0; d < Depth - 1; d++)
{
if(ball_tree[output_pos]) // true to the right.
{
ball_tree[output_pos] = 1 - ball_tree[output_pos];
output_pos = 2*output_pos + 1;
}
else // false to the left.
{
ball_tree[output_pos] = 1 - ball_tree[output_pos];
output_pos = 2 * output_pos;
}
}
}
std::cout << output_pos << std::endl;
}
这样做依旧超时,继续发现规律。可以发现球会让开关形成连续二进制数的表示(根节点是低位)。当放入第k个球时,开始的开关状态正好是二进制的k-1。然后就可以根据这个状态,计算出输出的位置。这样就把复杂度O(n^2)变成了O(n)。
最后版本:
#include <iostream>
#include <cmath>
#include <cstring>
static void ProcessDepthDAndIthBallDrop(int Depth, int I);
// int ball_num = pow(2, Depth - 1) + 1;
// int ball_tree[524288];
int main()
{
int num_test_case;
while(std::cin >> num_test_case && num_test_case != -1)
{
for(int i = 0; i < num_test_case; i++)
{
int D, I;
std::cin >> D >> I;
int ball_num = pow(2, D - 1);
I = (I-1)%ball_num;
ProcessDepthDAndIthBallDrop(D, I);
}
}
return 0;
}
static void ProcessDepthDAndIthBallDrop(int Depth, int I)
{
//std::memset(ball_tree, 0, 524288 * sizeof(int));
int output_pos = 1;
output_pos = 1;
for(int d = 0; d < Depth - 1; d++)
{
int res = I%2;
I = I >> 1;
if(res) // true to the right.
{
output_pos = 2*output_pos + 1;
}
else // false to the left.
{
output_pos = 2 * output_pos;
}
}
std::cout << output_pos << std::endl;
}