You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

divide_et_impera.py 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from SoSe24.algodat.foundation import AlgoDatArray, AlgoDatValue, read_int_sequence, MinusInf
  2. from time import perf_counter as pfc
  3. def in_between(z: AlgoDatArray, l: int, m: int, r: int) -> (AlgoDatValue, int, int):
  4. left_max = AlgoDatValue(MinusInf())
  5. left = AlgoDatValue(0)
  6. current_sum = AlgoDatValue(0)
  7. for i in range(m, l - 1, -1):
  8. current_sum += z[i]
  9. if current_sum > left_max:
  10. left_max.value = current_sum.value
  11. left.value = i
  12. right_max = AlgoDatValue(MinusInf())
  13. right = AlgoDatValue(0)
  14. current_sum.value = 0
  15. for i in range(m + 1, r + 1):
  16. current_sum += z[i]
  17. if current_sum > right_max:
  18. right_max.value = current_sum.value
  19. right.value = i
  20. return left_max + right_max, left, right
  21. def maxfolge_part(z: AlgoDatArray, l:int, r:int) -> (int, int, int):
  22. if l == r:
  23. return z[l].value, l, r
  24. m = (l + r) // 2
  25. left_sum, left_left, left_right = maxfolge_part(z, l, m)
  26. right_sum, right_left, right_right = maxfolge_part(z, m + 1, r)
  27. cross_sum, cross_left, cross_right = in_between(z, l, m, r)
  28. if left_sum >= right_sum and left_sum >= cross_sum:
  29. return left_sum, left_left, left_right
  30. elif right_sum >= left_sum and right_sum >= cross_sum:
  31. return right_sum, right_left, right_right
  32. else:
  33. return cross_sum, cross_left, cross_right
  34. def maxfolge3(z: AlgoDatArray) -> (int, int, int):
  35. return maxfolge_part(z, 0, z.size - 1)
  36. if __name__ == "__main__":
  37. z = read_int_sequence("../../seq3.txt")
  38. start = pfc()
  39. print(maxfolge3(z))
  40. print(f"Dauer: {pfc() - start:.4f}s")
  41. AlgoDatValue.summary()