From 82502079ee0b446bae2429895b194ac090802d80 Mon Sep 17 00:00:00 2001 From: Yodi FM Date: Sat, 10 Oct 2020 01:57:02 +0700 Subject: [PATCH] added sparse_table --- .vscode/c_cpp_properties.json | 21 +++++++++ Sparse Table/sparse_table.py | 80 +++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 .vscode/c_cpp_properties.json create mode 100644 Sparse Table/sparse_table.py diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..48dc9852 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,21 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "windowsSdkVersion": "10.0.18362.0", + "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.22.27905/bin/Hostx64/x64/cl.exe", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "msvc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/Sparse Table/sparse_table.py b/Sparse Table/sparse_table.py new file mode 100644 index 00000000..a36375c9 --- /dev/null +++ b/Sparse Table/sparse_table.py @@ -0,0 +1,80 @@ +# Python3 program to do range minimum +# query using sparse table +import math + +# Fills lookup array lookup[][] in +# bottom up manner. + + +def buildSparseTable(arr, n): + + # Initialize M for the intervals + # with length 1 + for i in range(0, n): + lookup[i][0] = arr[i] + + j = 1 + + # Compute values from smaller to + # bigger intervals + while (1 << j) <= n: + + # Compute minimum value for all + # intervals with size 2^j + i = 0 + while (i + (1 << j) - 1) < n: + + # For arr[2][10], we compare arr[lookup[0][7]] + # and arr[lookup[3][10]] + if (lookup[i][j - 1] < + lookup[i + (1 << (j - 1))][j - 1]): + lookup[i][j] = lookup[i][j - 1] + else: + lookup[i][j] = \ + lookup[i + (1 << (j - 1))][j - 1] + + i += 1 + j += 1 + +# Returns minimum of arr[L..R] + + +def query(L, R): + + # Find highest power of 2 that is smaller + # than or equal to count of elements in + # given range. For [2, 10], j = 3 + j = int(math.log2(R - L + 1)) + + # Compute minimum of last 2^j elements + # with first 2^j elements in range. + # For [2, 10], we compare arr[lookup[0][3]] + # and arr[lookup[3][3]], + if lookup[L][j] <= lookup[R - (1 << j) + 1][j]: + return lookup[L][j] + + else: + return lookup[R - (1 << j) + 1][j] + + +# Driver Code +if __name__ == "__main__": + + a = [7, 2, 3, 0, 5, 10, 3, 12, 18] + n = len(a) + MAX = 500 + + # lookup[i][j] is going to store minimum + # value in arr[i..j]. Ideally lookup table + # size should not be fixed and should be + # determined using n Log n. It is kept + # constant to keep code simple. + lookup = [[0 for i in range(MAX)] + for j in range(MAX)] + + buildSparseTable(a, n) + print(query(0, 4)) + print(query(4, 7)) + print(query(7, 8)) + +# This code is contributed by Rituraj Jain