트리/세그먼트 트리
최솟값과 최댓값
4gats
2024. 1. 13. 14:30
https://www.acmicpc.net/problem/10868
10868번: 최솟값
N(1 ≤ N ≤ 100,000)개의 정수들이 있을 때, a번째 정수부터 b번째 정수까지 중에서 제일 작은 정수를 찾는 것은 어려운 일이 아니다. 하지만 이와 같은 a, b의 쌍이 M(1 ≤ M ≤ 100,000)개 주어졌을 때는
www.acmicpc.net
구간합 구하기 문제에서
최솟값, 최댓으로 바꾸면 끝
<소스코드>
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
120
121
122
123
124
125
126
|
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <limits.h>
using namespace std;
vector<long> min_tree;
vector<long> max_tree;
void setminTree(int i)
{
while (i != 1)
{
min_tree[i / 2] = min(min_tree[i], min_tree[i-1]);
i -= 2;
}
}
void setmaxTree(int i)
{
while (i != 1)
{
max_tree[i / 2] = max(max_tree[i], max_tree[i - 1]);
i -= 2;
}
}
long getMin(int s, int e)
{
long tmpMin = LONG_MAX;
while (s <= e)
{
if (s % 2 == 1)
{
if (tmpMin > min_tree[s])
tmpMin = min_tree[s];
s++;
}
if (e % 2 == 0)
{
if (tmpMin > min_tree[e])
tmpMin = min_tree[e];
e--;
}
s = s / 2;
e = e / 2;
}
return tmpMin;
}
long getMax(int s, int e)
{
long tmpMax = LONG_MIN;
while (s <= e)
{
if (s % 2 == 1)
{
if (tmpMax < max_tree[s])
tmpMax = max_tree[s];
s++;
}
if (e % 2 == 0)
{
if (tmpMax < max_tree[e])
tmpMax = max_tree[e];
e--;
}
s = s / 2;
e = e / 2;
}
return tmpMax;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m, k;
cin >> n >> m;
int treeHeight = 0;
int Length = n;
while (Length != 0)
{
Length /= 2;
treeHeight++;
}
int treeSize = int(pow(2, treeHeight + 1));
int leftNodeStartIndex = treeSize / 2 - 1;
min_tree.resize(treeSize + 1);
max_tree.resize(treeSize + 1);
fill(min_tree.begin(), min_tree.end(), LONG_MAX);
fill(max_tree.begin(), max_tree.end(), LONG_MIN);
// 데이터를 리프 노드에 입력받기
for (int i = leftNodeStartIndex + 1; i <= leftNodeStartIndex + n; i++)
{
int x;
cin >> x;
min_tree[i] = x;
max_tree[i] = x;
}
setminTree(treeSize - 1);
setmaxTree(treeSize - 1);
for (int i = 0; i < m; i++)
{
int s, e;
cin >> s >> e;
s = leftNodeStartIndex + s;
e = leftNodeStartIndex + e;
cout << getMin(s, e) << ' ' << getMax(s, e) << '\n';
}
}
|
cs |