가장 높은 우선순위를 가진 요소가 먼저 나오는 자료구조
삽입, 삭제(pop)은 항상 O(log N) 이고, top()(가장 우선순위 높은 원소 조회)은 O(1)
가장 큰/작은 원소를 순식간에 추출해야 하는 문제에 최적함.
| 함수 | 설명 |
|---|---|
push(x) | 원소 x 삽입 (O(log n)) |
pop() | 가장 높은 우선순위 원소 제거 |
top() | 가장 높은 우선순위 원소 반환 (제거 X) |
empty() | 큐가 비었는지 확인 |
size() | 원소 개수 확인 |
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int> pq;
pq.push(5);
pq.push(2);
pq.push(8);
while (!pq.empty()) {
cout << pq.top() << " "; // 가장 큰 값부터 출력
pq.pop();
}
}
priority_queue<int, vector<int>, greater<int>> minHeap;
next_permutation / prev_permutation 사용하기
💠 next_permutation
주어진 범위를 사전순(lexicographical)으로 다음 순열로 바꿔줌
💠prev_permutation
주어진 범위를 사전순으로 이전 순열로 바꿔줌
⚠️ 원본 데이터는 정렬 상태여야 함!!
주어진 배열이 있을 때 n개의 원소 고르기
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector <int> nums = { 1, 2, 3, 4 };
vector<int> temp = { 1, 1, 0, 0 };
do {
for (int i = 0; i < nums.size(); i++) {
if (temp[i] == 1)
cout << nums[i] << ' ';
}
cout << endl;
} while (prev_permutation(temp.begin(), temp.end()));
}
}
#include <algorithm> 헤더 포함
시작점 부터 n번 째 까지만 정렬!
nth_element(v.begin(), v.begin() + n, v.end());
nth_element(v.begin(), v.begin() + n, v.end(), greater<>());
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = { 2, 3, 4 };
do {
cout << 1 << " " << nums[0] << " " << nums[1] << endl;
} while (next_permutation(nums.begin(), nums.end()));
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector <int> nums = { 1, 2, 3, 4 };
do {
for (int i = 0; i < nums.size() - 1; i++) {
cout << nums[i] << " ";
}
cout << endl;
} while (next_permutation(nums.begin() +1, nums.end()));
}
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = { 4, 1, 7, 3, 8, 5 };
priority_queue<int> result;
for (int num : nums) {
if (num >= 5) {
result.push(num);
}
}
//큐가 빌 때 까지 반복
while (!result.empty()) {
cout << result.top() << " ";
result.pop();
}
}
(출처: 스파르타코딩 내일배움캠프)