[BOJ][C++] λ°±μ€ 2357λ²: μ΅μκ°κ³Ό μ΅λκ° (Gold I)
λ¬Έμ
N(1 ≤ N ≤ 100,000)κ°μ μ μλ€μ΄ μμ λ, aλ²μ§Έ μ μλΆν° bλ²μ§Έ μ μκΉμ§ μ€μμ μ μΌ μμ μ μ, λλ μ μΌ ν° μ μλ₯Ό μ°Ύλ κ²μ μ΄λ €μ΄ μΌμ΄ μλλ€. νμ§λ§ μ΄μ κ°μ a, bμ μμ΄ M(1 ≤ M ≤ 100,000)κ° μ£Όμ΄μ‘μ λλ μ΄λ €μ΄ λ¬Έμ κ° λλ€. μ΄ λ¬Έμ λ₯Ό ν΄κ²°ν΄ 보μ.
μ¬κΈ°μ aλ²μ§ΈλΌλ κ²μ μ
λ ₯λλ μμλ‘ aλ²μ§ΈλΌλ μ΄μΌκΈ°μ΄λ€. μλ₯Ό λ€μ΄ a=1, b=3μ΄λΌλ©΄ μ
λ ₯λ μμλλ‘ 1λ², 2λ², 3λ² μ μ μ€μμ μ΅μ, μ΅λκ°μ μ°ΎμμΌ νλ€. κ°κ°μ μ μλ€μ 1μ΄μ 1,000,000,000μ΄νμ κ°μ κ°λλ€.
μ λ ₯
첫째 μ€μ N, Mμ΄ μ£Όμ΄μ§λ€. λ€μ Nκ°μ μ€μλ Nκ°μ μ μκ° μ£Όμ΄μ§λ€. λ€μ Mκ°μ μ€μλ a, bμ μμ΄ μ£Όμ΄μ§λ€.
μΆλ ₯
Mκ°μ μ€μ μ λ ₯λ°μ μμλλ‘ κ° a, bμ λν λ΅μ μ΅μκ°, μ΅λκ° μμλ‘ μΆλ ₯νλ€.
νμ΄
μΈκ·Έλ¨ΌνΈ νΈλ¦¬~
// νμ΄ : https://whkakrkr.tistory.com
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
ll INF = 1000000001;
int n,m, sz,x;
vector<ll> maxTree;
vector<ll> minTree;
void updateTree(int i, int val) {
int idx = i + sz - 1;
maxTree[idx] = val;
minTree[idx] = val;
while(idx>1) {
idx /= 2;
minTree[idx] = min(minTree[idx*2], minTree[idx*2+1]);
maxTree[idx] = max(maxTree[idx*2], maxTree[idx*2+1]);
}
}
int getMinMax(int a, int b, bool isMax) {
ll ans = isMax ? 0 : INF;
vector<ll>&tree = isMax ? maxTree : minTree;
int left = a + sz - 1;
int right = b + sz - 1;
while(left <= right) {
if(left%2 == 1) {
ans = isMax ? max(ans, tree[left]) : min(ans, tree[left]);
left++;
}
left /= 2;;
if(right%2 == 0) {
ans = isMax ? max(ans, tree[right]) : min(ans, tree[right]);
right--;
}
right /= 2;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
cin >> n >> m;
sz = pow(2, floor(log2(4*n)-1));
maxTree.assign(2*sz, 0);
minTree.assign(2*sz, INF);
for(int i=1; i<=n; i++) {
cin >> x;
updateTree(i, x);
}
int a, b;
while(m--) {
cin >> a >> b;
cout << getMinMax(a,b,false) << " " << getMinMax(a,b,true) << "\n";
}
return 0;
}