mirror of
https://github.com/iritmaximus/tira.git
synced 2026-10-12 19:13:47 +03:00
108 lines
2.9 KiB
Python
108 lines
2.9 KiB
Python
# for binarytree visualization
|
|
from math import log, floor, ceil
|
|
|
|
|
|
def count(n, k):
|
|
things = 0
|
|
print()
|
|
print("n:", n, "- k:", k)
|
|
|
|
if n <= 1:
|
|
return 1
|
|
elif k == 1:
|
|
return 1
|
|
elif n >= 3 and k == 2:
|
|
return 2
|
|
|
|
nodes = 0
|
|
for x in range(floor(log(n + 1, 2))):
|
|
nodes += 2**x
|
|
|
|
bottom_leaves = (
|
|
n - nodes + (2 ** (floor(log(n + 1, 2)) - 1) - ceil((n - nodes) / 2))
|
|
)
|
|
if bottom_leaves == 2 ** (floor(log(n + 1, 2))):
|
|
bottom_leaves = 0
|
|
# print("bottom", bottom_leaves)
|
|
|
|
if k == n:
|
|
if bottom_leaves != 0:
|
|
return bottom_leaves
|
|
else:
|
|
return 2 ** (floor(log(n + 1, 2)))
|
|
|
|
spots = 0
|
|
for x in range(1, ceil(log(n + 1, 2)) + 1):
|
|
values_below = n - 1
|
|
for y in range(1, x):
|
|
values_below -= 2**y
|
|
# print("lv", x, "--- val below", values_below)
|
|
print("lv:", x)
|
|
|
|
# jos n arvoja ei riitä syvyyteen x asti
|
|
# esim 8, 3 - 1, 2, 3 ja syvin olisi 4
|
|
if ceil(log(n + 1, 2) > k) and x == 1:
|
|
for z in range(k - 1):
|
|
spots += 2 * 2**z
|
|
print("removed bottom things")
|
|
return spots
|
|
|
|
# jos k on yhden tai ali päästä n eli voi olla vain 2 alimmalla
|
|
# tasolla
|
|
if n - k <= 1:
|
|
spots += bottom_leaves
|
|
if bottom_leaves % 2 != 0 and n > 5:
|
|
spots += 1
|
|
elif n - nodes != 0 and (n - nodes) % 2 != 0:
|
|
spots += 1
|
|
print("returned from n-k <= 1")
|
|
return spots
|
|
|
|
# if there is enough bottom values for higher than k values
|
|
if n - k >= values_below:
|
|
print(" n-k > below values ")
|
|
spots = n - 1
|
|
|
|
#
|
|
print(values_below)
|
|
if (values_below - (n - nodes)) // 2 + (n - nodes) > n - k and x > 1:
|
|
print("hiiiiih")
|
|
things += 1
|
|
|
|
# spots liian iso -> suurin mahdollinen
|
|
if spots >= n:
|
|
print("spots too much")
|
|
return n - 1
|
|
|
|
# jos viimeinen kierros, k arvoja riittää syvyyteen x
|
|
# ja alin epätäydellisen kerroksen leaveja on epätasainen määrä
|
|
# if (
|
|
# x == ceil(floor(log(n + 1, 2))) + 1
|
|
# and n - k >= x - 1
|
|
# and (n - nodes) % 2 != 0
|
|
# ):
|
|
# print("i dunno")
|
|
# spots += n - nodes
|
|
|
|
# jos k on suurempi kuin koko syvyys
|
|
# jos k suuremmat jäsenet riittävät täyttämään kaikki syvyydellä x
|
|
# isommalla puolella
|
|
if (
|
|
k >= ceil(log(n + 1, 2))
|
|
and (n - 1 - (n - nodes)) // 2 + (n - nodes) <= n - k
|
|
):
|
|
print("holy cwap lol")
|
|
return n - 1
|
|
|
|
print("got here")
|
|
# return ceil(spots)
|
|
return spots - things
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print(count(9, 3)) # 6
|
|
print(count(9, 4)) # 8
|
|
print(count(9, 6)) # 7
|
|
print(count(70, 34)) # 68
|
|
print(count(6, 4)) # 5
|