def main(): import sys input = sys.stdin.read().split() idx = 0 n = int(input[idx]) idx += 1 X = list(map(int, input[idx:idx+n])) idx += n A = list(map(int, input[idx:idx+n])) idx += n total = sum(A) max_a = max(A) sum_others = total - max_a if max_a > sum_others + 1: print(-1) return # Precompute the sorted list of other buttons for each i, ordered by distance and then X pre_sorted = [[] for _ in range(n)] for i in range(n): others = [] for j in range(n): if j != i: others.append((j, abs(X[j] - X[i]))) # Sort by distance, then by X[j] (smaller X first if distances are equal) others.sort(key=lambda x: (x[1], X[x[0]])) pre_sorted[i] = [j for j, _ in others] min_total = float('inf') # Iterate each possible starting button for start in range(n): if A[start] == 0: continue restA = A.copy() current = start restA[current] -= 1 total_d = 0 valid = True for _ in range(total - 1): found = False for j in pre_sorted[current]: if restA[j] > 0: total_d += abs(X[j] - X[current]) restA[j] -= 1 current = j found = True break if not found: valid = False break if valid and total_d < min_total: min_total = total_d if min_total == float('inf'): print(-1) else: print(min_total) if __name__ == "__main__": main()