fork(1) download
  1. from itertools import permutations, combinations
  2.  
  3. def max_abs_sum_gain(a1, b1, a2, b2):
  4. orig = abs(a1 - b1) + abs(a2 - b2)
  5. vals = [a1, b1, a2, b2]
  6. max_new = 0
  7. for a_group in combinations(range(4), 2):
  8. b_group = [i for i in range(4) if i not in a_group]
  9. for a_perm in permutations([vals[i] for i in a_group]):
  10. for b_perm in permutations([vals[i] for i in b_group]):
  11. new_v = abs(a_perm[0] - b_perm[0]) + abs(a_perm[1] - b_perm[1])
  12. max_new = max(max_new, new_v)
  13. return max_new - orig
  14.  
  15. def solve():
  16. import sys
  17. input = sys.stdin.read
  18. data = input().split()
  19.  
  20. idx = 0
  21. t = int(data[idx])
  22. idx += 1
  23. results = []
  24. for _ in range(t):
  25. n = int(data[idx])
  26. idx += 1
  27. k = int(data[idx])
  28. idx += 1
  29. a = list(map(int, data[idx:idx + n]))
  30. idx += n
  31. b = list(map(int, data[idx:idx + n]))
  32. idx += n
  33.  
  34. initial_v = sum(abs(a[i] - b[i]) for i in range(n))
  35. gains = []
  36.  
  37. for i in range(n):
  38. for j in range(i + 1, n):
  39. gain = max_abs_sum_gain(a[i], b[i], a[j], b[j])
  40. if gain > 0:
  41. gains.append(gain)
  42.  
  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. solve()
Success #stdin #stdout 0.13s 14096KB
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
0
9
-18
-20
274