BOJ 2357 최솟값과 최댓값

2020. 11. 4. 22:43·알고리즘/BOJ

www.acmicpc.net/problem/2357

 

2357번: 최솟값과 최댓값

N(1 ≤ N ≤ 100,000)개의 정수들이 있을 때, a번째 정수부터 b번째 정수까지 중에서 제일 작은 정수, 또는 제일 큰 정수를 찾는 것은 어려운 일이 아니다. 하지만 이와 같은 a, b의 쌍이 M(1 ≤ M ≤ 100

www.acmicpc.net

 

세그먼트 트리를 활용한 대표 문제 중 하나다.

처음에는 각 쿼리를 최소 트리, 최대 트리로 해줄까 하다가 pair로 한 번에 받아줬다.

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const int INF = 1e9 + 1;
vector<int> ar;
vector<pair<int, int>> tree;
int n, m, a, b;

pair<int, int> init(int s, int e, int node) {
	if (s == e) return tree[node] = { ar[s],ar[s] };
	auto p1 = init(s, (s + e) / 2, node * 2);
	auto p2 = init((s + e) / 2 + 1, e, node * 2 + 1);
	return tree[node] = { min(p1.first,p2.first),max(p1.second,p2.second) };
}

void query(int s, int e, int node, int l, int r, pair<int, int>& p) {
	if (l > e || r < s) return;
	if (l <= s && r >= e) {
		p.first = min(p.first, tree[node].first);
		p.second = max(p.second, tree[node].second);
		return;
	}
	query(s, (s + e) / 2, node * 2, l, r, p);
	query((s + e) / 2 + 1, e, node * 2 + 1, l, r, p);
}

int main() {
	ios::sync_with_stdio(false); cin.tie(0);

	cin >> n >> m;
	ar.resize(n);
	tree.resize(4 * n);

	for (int& i : ar) cin >> i;

	init(0, n - 1, 1);

	for (int i = 0; i < m; ++i) {
		pair<int, int> p(INF, 0);
		cin >> a >> b;
		query(0, n - 1, 1, a - 1, b - 1, p);
		cout << p.first << ' ' << p.second << '\n';
	}

	return 0;
}

 

'알고리즘 > BOJ' 카테고리의 다른 글

BOJ 1238 파티  (0) 2020.11.05
BOJ 9370 미확인 도착지  (0) 2020.11.05
BOJ 1261 알고스팟  (0) 2020.11.04
BOJ 14503 로봇 청소기  (0) 2020.11.03
BOJ 20055 컨베이어 벨트 위의 로봇  (0) 2020.11.02
'알고리즘/BOJ' 카테고리의 다른 글
  • BOJ 1238 파티
  • BOJ 9370 미확인 도착지
  • BOJ 1261 알고스팟
  • BOJ 14503 로봇 청소기
khyu2
khyu2
  • khyu2
    dev log
    khyu2
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 알고리즘
        • BOJ
        • Programmers
        • Algorithm
        • SWEA
      • 개발
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    소수
    알고리즘
    행렬 제곱
    유니온 파인드
    시뮬레이션
    팰린드롬
    BOJ
    프로그래머스
    MST
    코딩테스트 연습
    SWEA
    조합
    dp
    냅색
    이분 탐색
    피보나치 수
    BFS
    크루스칼
    완전 탐색
    분할 정복
    우선순위 큐
    이분탐색
    피사노 주기
    구현
    트리
    GREEDY
    다익스트라
    완전탐색
    dfs
    큐
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
khyu2
BOJ 2357 최솟값과 최댓값
상단으로

티스토리툴바