-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC2940.java
More file actions
119 lines (99 loc) · 3.13 KB
/
LC2940.java
File metadata and controls
119 lines (99 loc) · 3.13 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* LC2940
* This problem solved using Monotonic Decreasing Stack
*/
import java.util.*;
class BinaryIndexedTree {
private final int inf = 1 << 30;
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
Arrays.fill(c, inf);
}
public void update(int x, int y) {
while (x <= n) {
c[x] = Math.min(c[x], y);
x += x & -x;
}
}
public int query(int x) {
int mi = inf;
while (x > 0) {
mi = Math.min(mi, c[x]);
x -= x & -x;
}
return mi == inf ? -1 : mi;
}
}
public class LC2940 {
public static int[] leftmostBuildingQueries(int[] heights, int[][] queries) {
int n = heights.length;
int m = queries.length;
for (int i = 0; i < m; i++) {
if (queries[i][0] > queries[i][1]) {
queries[i] = new int[] { queries[i][1], queries[i][0] };
}
}
Integer[] idx = new Integer[m];
for (int i = 0; i < m; i++) {
idx[i] = i;
}
Arrays.sort(idx, (i, j) -> queries[j][1] - queries[i][1]);
int[] s = heights.clone();
Arrays.sort(s);
int[] ans = new int[m];
int j = n - 1;
BinaryIndexedTree tree = new BinaryIndexedTree(n);
for (int i : idx) {
int list = queries[i][0], r = queries[i][1];
while (j > r) {
int k = n - Arrays.binarySearch(s, heights[j]) + 1;
tree.update(k, j);
--j;
}
if (list == r || heights[list] < heights[r]) {
ans[i] = r;
} else {
int k = n - Arrays.binarySearch(s, heights[list]);
ans[i] = tree.query(k);
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Heights Arrays Size : ");
System.out.print("Enter Row : ");
int row = sc.nextInt();
System.out.print("Enter Column : ");
int col = sc.nextInt();
System.out.println();
int[][] heights = new int[row][col];
System.out.println("Enter The Heights Array Elements : ");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.printf("[%d][%d] : ", i, j);
heights[i][j] = sc.nextInt();
}
}
System.out.println();
System.out.print("Enter Queries Arrays Size : ");
int n = sc.nextInt();
System.out.println();
int[] queries = new int[n];
System.out.println("Enter The Queries Array Elements : ");
for (int i = 0; i < queries.length; i++) {
System.out.printf("[%d] : ", i);
queries[i] = sc.nextInt();
}
System.out.println();
int[] ans = leftmostBuildingQueries(queries, heights);
System.out.println("Answer : ");
for (int i = 0; i < ans.length; i++) {
System.out.printf("%d, ", ans[i]);
}
sc.close();
}
}