POJ 2756 二叉树 解题报告
编号:2756
考查点:简单递归,简单数学题
思路:第一反应是非递归算法,熟悉二叉树的性质的一眼就看出来是每次除2的关系,然后一次编译通过,一次AC,后来看了下递归算法,原来是两个变量的递归,仅仅12行代码.。
提交情况:10分钟,递归与非递归算法均实现,一次AC.递归为16MS,非递归0MS。
Source Code:
//POJ Grids 2756 Cycle Solution
#include
<
iostream
>
using namespace std;
int a[ 20 ];
int b[ 20 ];
bool ishave( int n)
{
for ( int i = 0 ;b[i] > 0 ;i ++ )
{
if (b[i] == n)
{
return true ;
}
}
return false ;
}
int main()
{
int x,y;
cin >> x >> y;
memset(a, 0 , sizeof a);
memset(b, 0 , sizeof b);
for ( int i = 0 ;x > 0 ;i ++ )
{
a[i] = x;
x >>= 1 ;
}
for ( int i = 0 ;y > 0 ;i ++ )
{
b[i] = y;
y >>= 1 ;
}
for ( int i = 0 ;;i ++ )
{
if (ishave(a[i]))
{
cout << a[i] << endl;
break ;
}
}
return 0 ;
}
// POJ Grids 2756 Recursive Solution
#include < iostream >
using namespace std;
int common( int x, int y)
{
if (x == y)
return x;
if (x > y)
return common(x / 2 ,y);
else
return common(x,y / 2 );
}
int main()
{
int x,y;
cin >> x >> y;
cout << common(x,y) << endl;
return 0 ;
}
using namespace std;
int a[ 20 ];
int b[ 20 ];
bool ishave( int n)
{
for ( int i = 0 ;b[i] > 0 ;i ++ )
{
if (b[i] == n)
{
return true ;
}
}
return false ;
}
int main()
{
int x,y;
cin >> x >> y;
memset(a, 0 , sizeof a);
memset(b, 0 , sizeof b);
for ( int i = 0 ;x > 0 ;i ++ )
{
a[i] = x;
x >>= 1 ;
}
for ( int i = 0 ;y > 0 ;i ++ )
{
b[i] = y;
y >>= 1 ;
}
for ( int i = 0 ;;i ++ )
{
if (ishave(a[i]))
{
cout << a[i] << endl;
break ;
}
}
return 0 ;
}
// POJ Grids 2756 Recursive Solution
#include < iostream >
using namespace std;
int common( int x, int y)
{
if (x == y)
return x;
if (x > y)
return common(x / 2 ,y);
else
return common(x,y / 2 );
}
int main()
{
int x,y;
cin >> x >> y;
cout << common(x,y) << endl;
return 0 ;
}
总结:在数据规模明显不会产生栈溢出时,应该考虑递归,毕竟代码短小美观的多.。
By Ns517
Time 09.02.05