2016-09-21 136 views
1

树如下:距离失败

 (1,1) 
    / \ 
    (2,1) (1,2) 
    /\ /\ 
(3,1)(2,3) (3,2)(1,3) 
     and onward 

根是(1,1),在树中的所有值都是元组。

Where (x,y) is an element of the tree: 
The leftChild will be (x+y,y) 
The rightChild will be (x,x+y) 

我正在构建一个函数,它可以找到根(1,1)的距离。我无法从头开始构建树,因为这太费时。

我发现距离正在搜索的元组有1个距离,我们必须用最小值减去最大值。我们可以倒退。

 1  2 
(3,2)->(1,2)->(1,1) 
(3,2)->(3-2,2) = (1,2)->(1,2-1) = (1,1) 
given this is always true: 
if x > y: 
    newtuple = (x-y,y) 
    distance += 1 
else if y > x: 
    newtuple = (x,y-x) 
    distance += 1 

然而,因为可能的测试案例甚至可能达到x = 10^50,这甚至太慢了。 (x,y)=(1,1),所以我发现正式地找到x与y的减法量,反之亦然,以使得x> y变为y < x,反之亦然。因此X - Y(一定的时间,比如说z)将使x小于y ... X - Y * z = y 通过代数找到z ... z =(YX)/( -Y)

这是到目前为止我的代码:

from decimal import Decimal 
import math 

def answer(M,F): 
    M = int(M) 
    F = int(F) 
    i = 0 
    while True: 
     if M == 1 and F == 1: 
      return str(i) 
     if M > F: 
      x = math.ceil((F-M)/(-F)) 
      M -= F*x 
     elif F > M: 
      x = math.ceil((M-F)/(-M)) 
      F -= M*x 
     else: 
      if F == M and F != 1: 
       return "impossible" 
     i += x 
     if M < 1 or F < 1: 
      return "impossible" 

    return str(i) 

而且它不是通过某种未知的测试案例,但通过了所有的测试情况下,我能想到的。我可能会失败哪些测试用例?我的代码在哪里错了?

p.s.使用十进制模块,只是从代码中删除,使更多的可读性。

+0

你能提供一个原始问题的链接吗? – Tempux

+0

@ sudomakeinstall2 http://pastebin.com/tJ2p3YN7 –

+0

是否来自在线法官,我可以测试我的实施情况? – Tempux

回答

0

地板部门允许没有损失,但可能错误-1,我认为下面的代码。

def answer(M,F): 
    M = int(M) 
    F = int(F) 
    i = 0 
    while True: 
     if M == 1 and F == 1: 
      return str(i) 
     if M > F: 
      x = F-M 
      x = x//(-F) 
      if F < M-(F*x): 
       x += 1 
      M -= F*x 
     elif F > M: 
      x = M-F 
      x = x//(-M) 
      if M < F-(M*x): 
       x += 1 
      F -= M*x 
     else: 
      if F == M and F != 1: 
       return "impossible" 
     i += x 
     if M < 1 or F < 1: 
      return "impossible" 

    return str(i)