
์ ์
์ ์ถ์ด์ง๋ง ์ฐ์ ์ถ์ด๋ฉฐ, ๊ฐ์ฅ ์ค์ํ ์ผ์ด ์ ์ผ ๋จผ์ ์ฒ๋ฆฌ๋๋ ๋๊ธฐ์ด์ด๋ผ๊ณ ์๊ฐํ๋ฉด ๋๋ค.
์ฐ์ ์์ ํ์ ๊ฐ๋จํ ํน์ง
C++ STL์์ priority_queue๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๊ฐ์ฅ ํฐ ์์๊ฐ ๋จผ์ ๋์ค๋(์ต๋ ํ) ๊ตฌ์กฐ์ด๋ค. ์ฆ ์ฐ์ ์์๊ฐ ๋๋ค๋ ๊ฒ์ ๊ฐ์ด ํฌ๋ค๋ ๊ฒ์ ์๋ฏธํ๋ค.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main()
{
priority_queue<int> pq;
pq.push(5);
pq.push(2);
pq.push(8);
//top() ๊ฐ์ฅ ์ฐ์ ์์๊ฐ ๋์ ์์๋ฅผ ๋ฐํ
cout<<"ํ์ฌ top"<<pq.top()<<endl; //8
pq.pop; //top(8) ์ ๊ฑฐ
}
์ต์ ํ๋ ๊ฐ๋ฅํ๋ฐ ์ธ ๋ฒ์งธ ํ ํ๋ฆฟ ์ธ์๋ฅผ greater<์๋ฃํ>์ผ๋ก ์ฃผ๋ฉด ๋๋ค.
priority_queue<int, vector<int>, greater<int>> minPq;
minPq.push(10);
minPq.push(5);
cout<<minPq.top()<<endl; // 5
์์ด๊ณผ ๊ด๋ จํ ๋ฌธ์ ๋ฅผ ๋ง๋ฌ์ ๋๋ next_permutation/ prev_permutation์ ์ฐ๋ฉด ๋๋ค. next_permutation์ ์ฃผ์ด์ง ๋ฒ์๋ฅผ ์ฌ์ ์์ผ๋ก ๋ค์ ์์ด๋ก ๋ฐ๊ฟ์ฃผ๊ณ prev_permutation์ ์ฃผ์ด์ง ๋ฒ์๋ฅผ ์ฌ์ ์์ผ๋ก ์ด์ ์์ด๋ก ๋ฐ๊ฟ์ฃผ๋ ๊ฒ์ด๋ค
์๋ณธ ๋ฐ์ดํฐ๋ ์ ๋ ฌ ์ํ์ฌ์ผ ํ๋ค. "์ฃผ์ด์ง ์์ด์ ๋ชจ๋ ์์ด ์์ฑ", "์ฌ์ ์์ผ๋ก ํน์ ์์ด ์ฐพ๊ธฐ"์ ๊ฐ์ ๋ฌธ์ ๋ฅผ ๋ง๋ฌ์ ๋ ์ ์ฉํ๋ค.
int main()
{
vector<int> v= {1,2,3};
for(int x: v) cout<<x<<" "; //123
cout<<endl;
next_permutation(v.begin(), v.end()));//132
for(int x: v) cout<<x<< " ";
cout<<endl;
}
nth_element๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค ์ด๊ฒ์ ํํฐ์ ๊ธฐ๋ฐ์ผ๋ก n๋ฒ์งธ๋ก ์์ ์์๋ฅผ ๋ฐฐ์ด์ n๋ฒ์งธ ์์น๋ก ๋ณด๋ธ ๋ค ๊ทธ ์ผ์ชฝ์ n๋ณด๋ค ์์ ์์๋ฅผ, ์ค๋ฅธ์ชฝ์ n๋ฒ์งธ๋ณด๋ค ํฐ ์์๋ค๋ก ๋ฐ์ ๋ ฌ์ ํ๋ค
int main()
{
vector<int> v= {9,1,4,7,2,6};
nth_element(v.begin(), v.begin()+2, v.end());
cout<< "3๋ฒ์งธ๋ก ์์ ์์: "<< v[2]<<endl;
}