You are given $n$ integers $wi (i = 0, 1, ..., n-1)$ to be sorted in ascending order.…
- User
You are given integers to be sorted in ascending order. You can swap two integers and . Each swap operation has a cost, which is the sum of the two integers . You can perform the operations any number of times.
Assistant
pythonn = int(input()) w = list(map(int, input().split())) sorted_w = sorted(w) value_to_pos = {v: i for i, v in enumerate(sorted_w)} visited = set() total_cost = 0 global_min = sorted_w[0] if n > 0 else 0 for x in w: if x not in visited: cycle = [] current = x while current not in visited: visited.add(current) cycle.append(current) current = w[value_to_pos[current]] sum_cycle = sum(cycle) min_cycle = min(cycle) k = len(cycle) if min_cycle == global_min: cost = (sum_cycle - min_cycle) + min_cycle * (k - 1) else: cost1 = (sum_cycle - min_cycle) + min_cycle * (k - 1) cost2 = sum_cycle + global_min * k cost = min(cost1, cost2) total_cost += cost print(total_cost)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.