lower_bound, upper_bound
lower_bound, upper_bound๋ฅผ int ํ์ ๊ณผ pair<>์์๋ ์ฌ์ฉํด๋ด ์๋ค.
algorithm ํค๋
lower_bound, upper_bound๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์ algorithm
๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ํ์ํฉ๋๋ค.
#include <algorithm>
์ ์ธ
lower_bound(์์ ์ดํฐ๋ ์ดํฐ, ๋ ์ดํฐ๋ ์ดํฐ, ์ง์ ๊ฐ)
upper_bound(์์ ์ดํฐ๋ ์ดํฐ, ๋ ์ดํฐ๋ ์ดํฐ, ์ง์ ๊ฐ)
๋ฆฌํด ๊ฐ
vector์์ lower_bound, upper_bound๋ฅผ ์ฌ์ฉํ ๋์ ๋ฆฌ ๊ฐ์ ์์๋ด ์๋ค.
lower_bound
lower_bound๋ vector์ ์์ ์ดํฐ๋ ์ดํฐ์ ๋ ์ดํฐ๋ ์ดํฐ ์ฌ์ด์์ ์ง์ ํ ๊ฐ ์ด์
์ ๊ฐ์ง๋ ์ต์ด์ ์ดํฐ๋ ์ดํฐ๋ฅผ ๋ฐํํฉ๋๋ค.
upper_bound
upper_bound๋ vector์ ์์ ์ดํฐ๋ ์ดํฐ์ ๋ ์ดํฐ๋ ์ดํฐ ์ฌ์ด์์ ์ง์ ํ ๊ฐ๋ณด๋ค ๋ ํฐ ๊ฐ
์ ๊ฐ์ง๋ ์ต์ด์ ์ดํฐ๋ ์ดํฐ๋ฅผ ๋ฐํํฉ๋๋ค.
์ธ๋ฑ์ค ๋ฐํ
vector๋ฅผ ๊ธฐ์ค์ผ๋ก ์ฒซ ์ดํฐ๋ ์ดํฐ ๊ฐ์ ๋นผ์ฃผ๋ฉด ์ธ๋ฑ์ค๊ฐ ๋ฐํ๋ฉ๋๋ค.
lower_bound(v.begin(), v.end(), num) - v.begin();
upper_bound(v.begin(), v.end(), num) - v.begin();
์์
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> adj= {2,4,6,1,7,8,3,1,5,7,9,3,2,1};
sort(adj.begin(),adj.end());
for(int i=0; i<adj.size();i++) cout << adj[i] << ' ';
// 1 1 1 2 2 3 3 4 5 6 7 7 8 9
cout << '\n';
int lowBoundIndex = lower_bound(adj.begin(),adj.end(), 4) - adj.begin();
int upperBoundIndex = upper_bound(adj.begin(),adj.end(),4) - adj.begin();
cout << lowBoundIndex << ' ' << upperBoundIndex << '\n';
// 7, 8
return 0;
}
pair<int,int>๋ฅผ ์ ์ฉํ ์์
๋น๊ต์ ๊ธฐ์ค์ด ๋ bool์ ๋ฐํํ๋ ํจ์๋ฅผ ๋ง๋ค๊ณ ๊ทธ ํจ์๋ฅผ ๋ค ๋ฒ์งธ ์ธ์๋ก ์ถ๊ฐํ๊ณ , ์ธ ๋ฒ์งธ ์ธ์์๋ make_pair()
๋ก ์ง์ ๊ฐ์ pair๋ก ์ ์ธํด ์ค๋๋ค.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool comp(const pair<int, int> &a, const pair<int,int> &b) {
return a.first < b.first;
}
int main(){
vector<pair<int,int>> adj= { {1,3},{2,5},{2,9},{9,20},{10,25},{5,2},{7,2},{8,9} };
sort(adj.begin(),adj.end());
for(int i=0; i<adj.size();i++) cout << adj[i].first << ' ' << adj[i].second << " | ";
// 1 3 | 2 5 | 2 9 | 5 2 | 7 2 | 8 9 | 9 20 | 10 25 |
cout << '\n';
int lowBoundIndex = lower_bound(adj.begin(),adj.end(), make_pair(5,0),comp) - adj.begin();
int upperBoundIndex = upper_bound(adj.begin(),adj.end(),make_pair(5,0),comp) - adj.begin();
cout << lowBoundIndex << ' ' << upperBoundIndex << '\n';
// 3, 4
return 0;
}
'Algorithm > ์ด๋ก ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๊ณ ๋ฆฌ์ฆ] ์ด์ง ํธ๋ฆฌ ํ์ (0) | 2022.03.10 |
---|---|
ํฌํฌ์ธํฐ ์๊ณ ๋ฆฌ์ฆ (0) | 2022.03.09 |
์ ํ, ๋ฒ๋ธ, ์ฝ์ ์ ๋ ฌ (0) | 2022.03.09 |
[์๊ณ ๋ฆฌ์ฆ] 8์ ๊ฐ์ ๊ตฌํ๊ธฐ (1~10์ต) (0) | 2022.03.09 |
Trie(ํธ๋ผ์ด) ์๊ณ ๋ฆฌ์ฆ (0) | 2022.03.08 |