8000 sqrt decomposition · Ismail0290/DSA-Bootcamp-Java@d623a5e · GitHub
[go: up one dir, main page]

Skip to content

Commit d623a5e

Browse files
sqrt decomposition
1 parent 3bb7a49 commit d623a5e

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import java.util.Arrays;
2+
3+
class Main {
4+
public static void main(String[] args) {
5+
int[] arr = {1, 3, 5, 2, 7, 6, 3, 1, 4, 8};
6+
int n = arr.length;
7+
8+
// build a blocks array
9+
int sqrt = (int) Math.sqrt(n);
10+
11+
int block_id = -1;
12+
13+
int[] blocks = new int[sqrt + 1];
14+
10000 15+
for(int i = 0; i < n; i++) {
16+
// new block is starting
17+
if(i % sqrt == 0) {
18+
block_id++;
19+
}
20+
blocks[block_id] += arr[i];
21+
}
22+
23+
System.out.println(query(blocks, arr, 2, 7, 3));
24+
}
25+
26+
public static int query(int[] blocks, int[] arr, int l, int r, int sqrt) {
27+
int ans = 0;
28+
29+
// left part
30+
while(l%sqrt != 0 && l<r && l!=0) {
31+
ans += arr[l];
32+
l++;
33+
}
34+
35+
// midle part
36+
while(l + sqrt <= r) {
37+
ans += blocks[l/sqrt];
38+
l += sqrt;
39+
}
40+
41+
// right part
42+
while(l <= r) {
43+
ans += arr[l];
44+
l++;
45+
}
46+
47+
return ans;
48+
}
49+
50+
public void update(int[] blocks, int[] arr, int i, int val, int sqrt) {
51+
int block_id = i / sqrt;
52+
blocks[block_id] += (val - arr[i]);
53+
arr[i] = val;
54+
}
55+
56+
}
926 KB
Binary file not shown.

0 commit comments

Comments
 (0)
0