伊甸园

题目:

GDOI2006一试第一题

求顺序表示的完全二叉树的第n个节点 在先序遍历的第几位

 

程序:

#include<iostream>

#include<cmath>

using namespace std;

 

int whole(int,int);

int layer(int);

int last_div(int);

int eden(int,int);

 

int main()

{

int number;

int position;

cout<<"number of the nodes"<<' ';

cin>>number;

cout<<"in eden's sort:"<<' ';

cin>>position;

int result=eden(position,number);

cout<<result;

return 0;

}

 

int whole(int div,int num)

{

int full=pow(double(2),double(div-1))-1;

int full_lst=pow(double(2),double(div-1));

int lst=full_lst<last_div(num)?full_lst:last_div(num);

return full+lst;

}

int layer(int num)

{

return int(log(num)/log(2))+1;

}

int last_div(int num)

{

return num-pow(double(2),double(layer(num)-1));

}

int eden(int pos,int num)

{

if(pos==1||pos==0) return 2;

else if(pos%2==0) return eden(pos/2,num)+1;

else if(pos%2==1) return whole(layer(pos),num)+eden((pos-1)/2,num)+1;

}

你可能感兴趣的:(伊甸园)