This subject requires the path length from a binary tree node to the root node. The basic idea is to compare a and B. If a is large, the current node is left child, a-B is the left Number of the parent node. the right number of the parent node is equal to the current right number. If B is large, the current node is the right child. Similarly, you can find the parent node, the traversal ends until the parent node is (1, 1.
When the original recursive algorithm times out, consider the special circumstances of a = 1 or B = 1, and use the multiples of A and B to speed up the traversal.
Source code
Problem:2499 |
|
User: Yangliuacmer |
Memory:244 K |
|
Time:0 ms |
Language:C ++ |
|
Result:Accepted |
# Include <iostream> using namespace STD; void travelcount (Int & L, Int & R, int A, int B) {/* Original recursive algorithm, not optimized, tleif (A = 1 & B = 1) {return;} If (A> B) {// (A, B) is the left child travelcount (++ l, r, A-B, B);} else travelcount (L, ++ R, a, B-); * // change the recursive form to the loop form (non-recursive form) while (! = 1 | B! = 1) {if (a = 1) {// if only a is 1, only the right path is taken, which must be the right child, directly calculate the difference and convert it into steps R + = B-A; break;} If (B = 1) {L + = A-B; break ;} // use the multiples of A and B to take multiple steps each time to speed up the traversal. If (A> B) {L + = A/B; a-= B * (a/B);} else {R + = B/a; B-= A * (B/A) ;}} int main () {int N, A, B, l, R, I = 1; CIN> N; while (n --) {CIN> A> B; L = r = 0; travelcount (L, R, a, B); cout <"Scenario #" <(I ++) <":" <Endl; cout <L <"" <r <Endl;} return 0 ;}
Reference http://www.cnblogs.com/allensun/archive/2010/11/08/1872028.html