fork(1) download
  1. # File: optimal_game_value.py
  2.  
  3. def max_abs_sum_gain(a1, b1, a2, b2):
  4. # Computes the maximum possible gain in value from Bahamin's optimal swap
  5. orig = abs(a1 - b1) + abs(a2 - b2)
  6. values = [a1, b1, a2, b2]
  7. max_new = 0
  8. for x1 in values:
  9. for x2 in values:
  10. if x1 == x2: continue
  11. remaining = values[:]
  12. remaining.remove(x1)
  13. remaining.remove(x2)
  14. y1, y2 = remaining
  15. new_v = abs(x1 - y1) + abs(x2 - y2)
  16. max_new = max(max_new, new_v)
  17. return max_new - orig
  18.  
  19. def solve():
  20. import sys
  21. input = sys.stdin.read
  22. data = input().split()
  23.  
  24. idx = 0
  25. t = int(data[idx]); idx += 1
  26. results = []
  27. for _ in range(t):
  28. n = int(data[idx]); idx += 1
  29. k = int(data[idx]); idx += 1
  30. a = list(map(int, data[idx:idx+n])); idx += n
  31. b = list(map(int, data[idx:idx+n])); idx += n
  32.  
  33. initial_v = sum(abs(a[i] - b[i]) for i in range(n))
  34. gains = []
  35.  
  36. # Try only i and i+1 to limit complexity (O(n))
  37. for i in range(n - 1):
  38. gain = max_abs_sum_gain(a[i], b[i], a[i+1], b[i+1])
  39. if gain > 0:
  40. gains.append(gain)
  41.  
  42. # Sort and apply top k gains
  43. gains.sort(reverse=True)
  44. final_v = initial_v + sum(gains[:k])
  45. results.append(str(final_v))
  46.  
  47. print("\n".join(results))
  48.  
  49. # Uncomment below if running directly:
  50. # if __name__ == "__main__":
  51. # solve()
Success #stdin #stdout 0.07s 13992KB
stdin
5
2 1
1 7
3 5
3 2
1 5 3
6 2 4
5 4
1 16 10 10 16
3 2 2 15 15
4 1
23 1 18 4
19 2 10 3
10 10
4 3 2 100 4 1 2 4 5 5
1 200 4 5 6 1 10 2 3 4
stdout
Standard output is empty