二叉树- 数学加速运算

来源:互联网 发布:钩针设计软件 编辑:程序博客网 时间:2024/06/15 13:47

poj1501 Binary Tree

解题思路:

//每一次向左子树的深入都会改变左值+ 父节点的右值
//每一次沿有字数的深入都会改变右值+ 父节点的左值
//数据量太大,不能考虑从上到下的模拟
//第一个想法:对于每一个节点,执行find_father的操作 执行总共只需要进行log(n)次 但事实上树高并不是log(n)的而是n的
//把原来的+-查找变成除法查找 其实主要是考察数学加速计算 改递归为循环

代码如下:

#include <iostream>using namespace std;int T;int a, b;int cntl,cntr;// void find_f(int x, int y)// {//     if(x == y) return;//     if(x > y)//     {//         cntl++;//         find_f(x - y, y);//     }//     else if(x < y)//     {//         cntr++;//         find_f(x, y - x);//     }// }int main(){#ifndef ONLINE_JUDGE    freopen("input.txt", "r", stdin);    freopen("output.txt", "w", stdout);#endif    scanf("%d",&T);    for(int i = 1; i <= T; i++)    {        cntl = 0; cntr = 0;        printf("Scenario #%d:\n",i);        scanf("%d%d",&a,&b);        while(a != 1 || b != 1)        {            if(a > b)            {                int c = a / b;                a %= b;//只有当b == 1时 a为0                if(!a) --c, a= 1;                cntl += c;             }            else            {                int c = b / a;                b %= a;                if(!b) --c, b = 1;                cntr += c;            }        }        printf("%d %d\n",cntl,cntr);        printf("\n");    }#ifndef ONLINE_JUDGE    fclose(stdin); fclose(stdout);#endif    return 0;}
原创粉丝点击