Skip to content

Commit 35d5945

Browse files
authored
Merge pull request #266 from AlgorithmWithGod/lkhyun
[20250319] BOJ / 골드1 / 최솟값과 최댓값 / 이강현
2 parents b0b4d15 + d380629 commit 35d5945

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
class Node{
6+
long min;
7+
long max;
8+
Node(long min,long max){
9+
this.min = min;
10+
this.max = max;
11+
}
12+
}
13+
public class Main {
14+
static int N;
15+
static int M;
16+
static long[] arr;
17+
static Node[] tree;
18+
public static void main(String[] args) throws Exception {
19+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
20+
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
21+
StringTokenizer st = new StringTokenizer(br.readLine());
22+
N = Integer.parseInt(st.nextToken());
23+
M = Integer.parseInt(st.nextToken());
24+
arr = new long[N*4];
25+
tree = new Node[N*4];
26+
27+
for(int i=1;i<=N;i++){
28+
arr[i] = Long.parseLong(br.readLine());
29+
}
30+
init(1,1,N);
31+
for(int i=0;i<M;i++){
32+
st = new StringTokenizer(br.readLine());
33+
int left = Integer.parseInt(st.nextToken());
34+
int right = Integer.parseInt(st.nextToken());
35+
Node n = query(1,1,N,left,right);
36+
bw.write(n.min+" "+n.max+"\n");
37+
}
38+
bw.close();
39+
}
40+
public static void init(int cur, int start, int end){
41+
if(start == end){
42+
tree[cur] = new Node(arr[start],arr[start]);
43+
return;
44+
}
45+
46+
init(cur*2,start,(start+end)/2);
47+
init(cur*2 + 1, (start+end)/2 + 1, end);
48+
tree[cur] = new Node(Math.min(tree[cur*2].min,tree[cur*2 + 1].min),
49+
Math.max(tree[cur*2].max,tree[cur*2 + 1].max));
50+
}
51+
public static Node query(int cur, int start, int end, int left, int right){
52+
if(left>end || right<start) return null;
53+
if(left<=start && right>=end) return tree[cur];
54+
55+
Node l = query(cur*2,start,(start+end)/2,left,right);
56+
Node r = query(cur*2+1,(start+end)/2 + 1, end,left,right);
57+
if(l==null)return r;
58+
else if(r==null) return l;
59+
else return new Node(Math.min(l.min,r.min),Math.max(l.max,r.max));
60+
}
61+
}
62+
```

0 commit comments

Comments
 (0)