forked from AllAlgorithms/java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmentTree.java
More file actions
Latest commit
89 lines (73 loc) · 2.43 KB
/
Copy pathSegmentTree.java
File metadata and controls
89 lines (73 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
importjava.util.*;
importjava.lang.*;
importjava.io.*;
classSegmentTree {
intst[];
Segment(int []arr, intn)
{
intx = (int) Math.ceil((Math.log(n)/Math.log(2)));
intmax_size = 2 *(int) (Math.pow(2,x) - 1);
st = newint[max_size];
constSegmentUtil(arr,0,n-1,0);
}
intconstSegmentUtil(int[] arr, intss, intse, intsi) {
if (ss == se) {
st[si] = arr[ss];
returnarr[ss];
}
intmid = getMid(ss, se);
st[si] = max(constSegmentUtil(arr, ss, mid, 2 * si + 1), constSegmentUtil(arr, mid + 1, se, 2 * si + 2));
returnst[si];
}
intgetMid(ints, inte) {
returns + (e - s) / 2;
}
intmax(inta, intb) {
if (a > b) {
returna;
} else {
returnb;
}
}
voidprint() {
for (inti = 0; i < st.length; i++) {
System.out.print(st[i]);
}
}
intgetMaxUtil(intss, intse, intqs, intqe, intsi) {
if (qs <= ss && qe >= se) {
returnst[si];
}
if (se < qs || ss > qe) {
return0;
}
intmid = getMid(ss, se);
returnmax(getMaxUtil(ss, mid, qs, qe, 2 * si + 1), getMaxUtil(mid + 1, se, qs, qe, 2 * si + 2));
}
intgetMax(intn, intqs, intqe) {
if (qs > qe || qs < 0 || qe > n - 1) {
return -1;
}
returngetMaxUtil(0, n - 1, qs, qe, 0);
}
publicstaticvoidmain(String[] args) throwsjava.lang.Exception {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
intt = Integer.parseInt(br.readLine());// for testcase
String[] temp = br.readLine().split(" ");// taking array as string
int[] arr = newint[t];
for (inti = 0; i < t; i++) // to convert array of string to array of integers
{
arr[i] = Integer.parseInt(temp[i]);
}
Segmenttree = newSegment(arr, arr.length);
// tree.print();
intq = Integer.parseInt(br.readLine()); // no of queries
while (q-- != 0) {
String[] temp1 = br.readLine().split(" ");
ints = Integer.parseInt(temp1[0]); // q1
inte = Integer.parseInt(temp1[1]); // q2
System.out.println(tree.getMax(arr.length, s - 1, e - 1)); // maximum in range [q1,q2]
// System.out.println(getMax(arr,n,s,e));
}
}
}