Create Sort and &
Swadhin Biswas committed 1 years ago
f7e99df
1 parent 8ba3bbc
commit f7e99df
1 file changed
+53 -0
Showing 1 changed file+53-0
▼Sort and &
+53-0
| @@ -0,0 +1,53 @@ | ||
1 | +import sys | |
2 | +from typing import List, Tuple | |
3 | + | |
4 | +def get_optimal_swaps(n: int, arr: List[int]) -> Tuple[int, List[Tuple[int, int]]]: | |
5 | + # Create position array to quickly find where each number is | |
6 | + pos = [0] * (n + 1) | |
7 | + for i in range(n): | |
8 | + pos[arr[i]] = i + 1 # 1-based indexing | |
9 | + | |
10 | + operations = [] | |
11 | + total_cost = 0 | |
12 | + | |
13 | + # For each position, put the correct number there | |
14 | + for i in range(1, n + 1): | |
15 | + if pos[i] != i: | |
16 | + # Find where the current number i is | |
17 | + curr_pos = pos[i] | |
18 | + | |
19 | + # Calculate cost for this swap | |
20 | + cost = i & curr_pos | |
21 | + total_cost += cost | |
22 | + | |
23 | + # Update positions after swap | |
24 | + num_at_i = arr[i - 1] | |
25 | + arr[curr_pos - 1], arr[i - 1] = arr[i - 1], arr[curr_pos - 1] | |
26 | + pos[i] = i | |
27 | + pos[num_at_i] = curr_pos | |
28 | + | |
29 | + # Record the swap operation | |
30 | + operations.append((i, curr_pos)) | |
31 | + | |
32 | + return total_cost, operations | |
33 | + | |
34 | +def main(): | |
35 | + # For faster input | |
36 | + input = sys.stdin.readline | |
37 | + | |
38 | + t = int(input()) | |
39 | + for _ in range(t): | |
40 | + n = int(input()) | |
41 | + arr = list(map(int, input().split())) | |
42 | + | |
43 | + # Get minimum cost and operations | |
44 | + total_cost, operations = get_optimal_swaps(n, arr) | |
45 | + | |
46 | + # Output results | |
47 | + print(total_cost) | |
48 | + print(len(operations)) | |
49 | + for i, j in operations: | |
50 | + print(i, j) | |
51 | + | |
52 | +if __name__ == "__main__": | |
53 | + main() | |
0 | 54 | |