例题6-6 UVA679

来源:互联网 发布:阿里云cdn公共库 编辑:程序博客网 时间:2024/05/16 19:44

原题:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=620

思路:对于一个节点k,两个子节点分别是2*k  (左) 2*k+1 (右),如果直接开数组模拟会超时,由前两个小球可以知道第一个左节点,第二个右节点。那么根据编号就能够得出落在哪个节点,奇数的小球相当与往左走的第(I+1)/2 个小球,偶数的I/2个小球。

Code:

#include <iostream>#include <cstdio>#include <string.h>using namespace std; int main(){int T;ios_base::sync_with_stdio(false); cin.tie(0);while(cin >> T){if( T == -1 ) break;int d,I;while( T-- ){cin >> d >> I;int k = 1 ;for( int i = 0 ; i < d - 1 ; i ++ ){       //知道是第几个落入根节点左右子树就可以知道到叶子的路径if( I % 2 ){k = 2 * k ; I = (I+1)/2;}else{k = 2 * k + 1 ; I = I / 2 ;}}cout << k << endl;}}return 0;}

原创粉丝点击