• 《Algorithm in C》by Sedgewick 读书笔记


    Update: July 4, 2014

    Chap 5:

    At the beginning, he mentioned that: recursion is a divide-and-conquer method. Although many algorithms can be solved in simple recursion but it is often an equally algorithm lies in the details of a nonrecursive implementation?(没搞懂)

    Divide-and-conquer programs normally do not reduce to trivial loops since they have 2 recursive calls and do had divided without overlap so no excessive recomputing.

    /*
    * method 1 of ruler: @ p54
    */
    
    rule(int l, int r, int h){
       ...
       mark(m,h);
       rule(l, m, h-1);    // NOTICE: not to m-1;
       rule(m, r, h-1);   // NOTICE: not from m+1;
    }

    as shown in Fig 5.4. The tree plot of calling recursive method. shows the difference of changing the order of calling 2 recursions.

    In compiler, it actually removes recursion. One well-known tech is end-recursion removal. Firstly use goto instead of looping. Then remove the 2nd recursion (this is easy since there is no code after it). But the other recursion needs more work to remove, which is by using the normal way for any procedure call:“push the values of local variables and the address of the next instruction on a stack, set the values of parameters to the procedure and goto the beginning of the procedure.” Then, when the procedure has completes, it must “pop the return address and values of local variables from stack(注意顺序,因为stack是LIFO), reset the variables, and goto the return address.”

    This is the same as the way Sedgewick's code:

    traverse(struct node *t){
    l:   if(t==z) goto s;
        visit(t);
        push(t); t=t->l; goto l;  // when call procedure, push var, return addr into stack. Then 
                   // change the var and goto the begining of the procedure. Also, when complete 
                  // it should go to s, which pop var and goto return addr.
    r:  t = t->r; goto l;         
    s: if(stackEmpty()) goto x;  // when complete, it pop return addr, var out and goto the return addr.
        t = pop(); goto r;            // since the return addr is the ending recursive which is a constant, so 
    x: ;                 // don't need to push or pop the addr. Also,
    
    }
  • 相关阅读:
    PC版优酷的一次异常
    颜宁开讲啦谈理性思考
    李彦宏开讲啦谈判断能力
    尝试插入cctv视频
    selenium中quit与close方法的区别
    CodeForces 131C The World is a Theatre(组合数)
    CodeForces 446A DZY Loves Sequences(dp)
    UVA 1631 Locker(密码锁)(dp记忆化搜索)
    UVA 1630 Folding(串折叠)(dp记忆化搜索)
    UVA 1629 Cake slicing(切蛋糕)(dp记忆化搜索)
  • 原文地址:https://www.cnblogs.com/gpuasic/p/3825456.html
Copyright © 2020-2023  润新知