├── Algorithm.txt ├── CODE.py └── Problem explanation.txt /Algorithm.txt: -------------------------------------------------------------------------------- 1 | This code appears to be an implementation of two different algorithms: Binary Indexed Tree (BIT) and Merge Sort. Let's go through each part and explain its functionality. 2 | 3 | The `BinaryIndexedTree` class represents a Binary Indexed Tree data structure. Here's a breakdown of its methods: 4 | 5 | - `__init__(self, sz)`: Initializes the Binary Indexed Tree with a given size `sz` and creates an array `tree` of zeros with size `sz`. 6 | 7 | - `update(self, idx, val)`: Updates the Binary Indexed Tree at index `idx` by adding the value `val` to it. This method uses the binary representation of the index to determine the relevant positions in the tree to update. 8 | 9 | - `read(self, idx)`: Computes the cumulative sum from index 1 to `idx` in the Binary Indexed Tree. It iteratively adds the values from the tree based on the binary representation of the index. 10 | 11 | The code after the `if __name__ == '__main__':` block seems to use the `BinaryIndexedTree` class to calculate the number of inversions in an array. 12 | 13 | Here's an explanation of that part of the code: 14 | 15 | 1. Read the input `t`, which represents the number of test cases. 16 | 17 | 2. Iterate `t` times: 18 | a. Read the input `n`, the size of the array. 19 | b. Read the array elements and store them in `arr` as a list of integers. 20 | 21 | Note: The `raw_input()` function is used in Python 2 to read input from the user, while `input()` is used in Python 3. Since the code has `#!/bin/python` at the beginning, it suggests that the code is meant to be run using Python 2. 22 | 23 | 3. Initialize a variable `cnt` to keep track of the number of inversions. 24 | Initialize an instance of `BinaryIndexedTree` called `bit` with a size of `10**7 + 1`. 25 | 26 | 4. Iterate over the elements of the `arr` list in reverse order: 27 | a. Update the `bit` by adding 1 to the element `val`. 28 | b. Add the cumulative sum of elements less than `val` in the `bit` to `cnt`. 29 | 30 | 5. Print the value of `cnt`, which represents the number of inversions in the array. 31 | 32 | The second part of the code implements the Merge Sort algorithm, which counts the number of inversions in an array. However, it seems to be unrelated to the rest of the code and does not appear to be used. -------------------------------------------------------------------------------- /CODE.py: -------------------------------------------------------------------------------- 1 | 2 | class BinaryIndexedTree(): 3 | def __init__(self, sz): 4 | self.sz = sz 5 | self.tree = [0] * sz 6 | 7 | def update(self, idx, val): 8 | while (idx <= self.sz): 9 | self.tree[idx] += val 10 | idx += (idx & -idx) 11 | def read(self, idx): 12 | sum = 0 13 | while (idx > 0): 14 | sum += self.tree[idx] 15 | idx -= (idx & -idx) 16 | return sum 17 | 18 | if __name__ == '__main__': 19 | t = input() 20 | for _ in range(t): 21 | n = input() 22 | arr = map(int, raw_input().split()) 23 | 24 | cnt = 0 25 | bit = BinaryIndexedTree(10**7+1) 26 | for val in reversed(arr): 27 | bit.update(val, 1) 28 | cnt += bit.read(val-1) 29 | print cnt 30 | #!/bin/python 31 | 32 | import math 33 | import os 34 | import random 35 | import re 36 | import sys 37 | 38 | 39 | def mergeSort(alist): 40 | inversion_count = 0 41 | 42 | n = len(alist) 43 | if n == 1: 44 | return 0 45 | 46 | mid = len(alist) // 2 47 | lefthalf = alist[:mid] 48 | righthalf = alist[mid:] 49 | 50 | n1 = len(lefthalf) 51 | n2 = len(righthalf) 52 | 53 | inversion_count += mergeSort(lefthalf) 54 | inversion_count += mergeSort(righthalf) 55 | 56 | i = 0 57 | j = 0 58 | k = 0 59 | while i < n1 and j < n2: 60 | if lefthalf[i] <= righthalf[j]: 61 | alist[k] = lefthalf[i] 62 | i = i + 1 63 | else: 64 | alist[k] = righthalf[j] 65 | j = j + 1 66 | inversion_count += n1 - i 67 | k = k + 1 68 | 69 | while i < n1: 70 | alist[k] = lefthalf[i] 71 | i = i + 1 72 | k = k + 1 73 | 74 | while j < n2: 75 | alist[k] = righthalf[j] 76 | j = j + 1 77 | k = k + 1 78 | 79 | return inversion_count 80 | 81 | 82 | if __name__ == '__main__': 83 | 84 | t = int(raw_input()) 85 | 86 | for t_itr in xrange(t): 87 | n = int(raw_input()) 88 | 89 | arr = map(int, raw_input().rstrip().split()) 90 | 91 | result = mergeSort(arr) 92 | 93 | print result -------------------------------------------------------------------------------- /Problem explanation.txt: -------------------------------------------------------------------------------- 1 | In Insertion Sort, each element in the array is compared with the elements before it and inserted into its correct position in the sorted subarray. The number of times an element needs to be shifted during this process can be used as a measure of how far it is from its sorted position. 2 | 3 | Let's consider an example to illustrate this: 4 | 5 | Suppose we have an array `[4, 2, 1, 3]`. We start with an empty sorted subarray and iterate through the elements from left to right. For each element, we compare it with the elements before it in the sorted subarray and shift them to the right if they are greater. 6 | 7 | - For the second element `2`, it is smaller than the first element `4`, so we shift `4` one position to the right. 8 | - For the third element `1`, it is smaller than both `4` and `2`, so we shift `4` and `2` one position to the right. 9 | - For the fourth element `3`, it is greater than `1` but smaller than `4`, so we insert it after `1` and before `4` without any shift. 10 | 11 | In this example, the first element `4` did not require any shift. The second element `2` required one shift. The third element `1` required two shifts. The fourth element `3` required one shift. 12 | 13 | The total number of shifts for this array is `0 + 1 + 2 + 1 = 4`. 14 | 15 | If we generalize this process for any array of size `N`, we can see that the number of shifts for the `i`th element is the number of elements greater than it in the subarray before it. This can be denoted as `ki`. 16 | 17 | Therefore, the total number of shifts for the entire array will be the sum of all the individual shifts: `k1 + k2 + ... + kN`. 18 | 19 | In summary, to calculate the total number of shifts in Insertion Sort, we need to count the number of elements greater than each element in the sorted subarray before it and sum up these counts for all elements in the array. --------------------------------------------------------------------------------