티스토리 뷰
1655번: 가운데를 말해요
첫째 줄에는 수빈이가 외치는 정수의 개수 N이 주어진다. N은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수이다. 그 다음 N줄에 걸쳐서 수빈이가 외치는 정수가 차례대로 주어진다. 정수는 -1
www.acmicpc.net
문제풀이
정수를 하나씩 받을 때마다 중앙값을 출력하는 문제다.
이 문제는 우선순위 큐 2개를 이용해서 풀 수 있다.
기본적으로 우선순위 큐가 Heap 구조이므로 Max Heap과 Min Heap 두 개를 선언한다.
비교함수를 따로 정해주지 않으면 기본적으로 내림차순에 따라 정렬한다. (Max Heap)
// Min Heap
priority_queue<int, vector<int, int>, greater<int>> minheap;
// Max Heap
priority_queue<int> maxheap;
중간값을 찾아야 하므로 두 큐의 크기는 같아야 한다.
우선 입력 받은 정수를 두 큐의 크기가 같도록 큐에 넣어준다.
그 후 max heap의 top과 min heap의 top을 비교했을 때 min heap의 top이 더 크다면
정렬이 제대로 되지 않은 상태이므로 max heap과 min heap의 top을 swap해준다.
수빈이가 외친 수의 개수가 짝수개라면 중간에 있는 두 수 중에서 작은 수를 말하면 되므로
짝수든 홀수든 max heap의 top을 출력해주면 된다.
C++ 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <queue> | |
using namespace std; | |
int main() | |
{ | |
ios::sync_with_stdio(false); | |
cin.tie(NULL); | |
cout.tie(NULL); | |
int n, k; | |
cin >> n; | |
priority_queue<int> maxheap; // 중간값보다 큼 | |
priority_queue<int, vector<int>, greater<int>> minheap; // 중간값보다 작음 | |
for (int i = 1; i <= n; i++) { | |
cin >> k; | |
if (maxheap.size() == minheap.size()) | |
maxheap.push(k); | |
else | |
minheap.push(k); | |
if (!maxheap.empty() && !minheap.empty() && minheap.top() < maxheap.top()) { | |
int a = minheap.top(); | |
int b = maxheap.top(); | |
minheap.pop(); maxheap.pop(); | |
minheap.push(b); | |
maxheap.push(a); | |
} | |
cout << maxheap.top() << '\n'; | |
} | |
return 0; | |
} |
'Problem Solving > BOJ' 카테고리의 다른 글
[BOJ 2263] 트리의 순회 C++/Kotlin (0) | 2021.07.20 |
---|---|
[BOJ 1074] Z C++ (0) | 2021.07.20 |
[BOJ 2696] 중앙값 구하기 C++ (0) | 2021.07.20 |
[BOJ 2900] 프로그램 C++ (0) | 2021.07.19 |
[BOJ 1005] ACM Craft C++ (0) | 2021.07.16 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- SWEA
- programmers
- 배열
- 트리
- 재귀
- 이분 탐색
- BOJ
- 문자열
- 스택
- 투 포인터
- BFS
- Two Pointer
- 두 포인터
- 그래프
- 위상 정렬
- 구현
- C++
- SW Expert Academy
- Java
- 큐
- 자바
- Kotlin
- dfs
- 백준
- algorithm
- 정렬
- 프로그래머스
- 분할 정복
- 브루트포스
- 알고리즘
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함