※ 이번 문제에서 알게된 점
§ sort(v.begin(), v.end(), custom_func) 함수
1. 먼저 vector에 include 되어 있는 pair를 선언해 입력을 받으면 다음과 같다.
vector< pair<int, int> > p;
for (int i = 0; i < num; i++) {
int n1, n2; cin >> n1 >> n2;
p.push_back(make_pair(n1, n2));
}
2. 그 후 sort를 해줘야 하는데, 이때 문제는 sort를 해주면 p.first를 기준으로 정렬 된다는 것.
그래서 사용자가 만든 함수로 sort(v.begin(), v.end(), custom_func) 의 custom_func에 넣어서
p.second 기준으로 정렬되도록 해야한다. 이때, custom_func의 결과값은 0, 1이 나와야 하며 보통 bool type이다.
bool compare(pair<int, int> a, pair<int, int> b) {
if (a.second == b.second)
return a.first < b.first; // a.first가 작으면 true. 즉 작은게 앞에 배치가 된다.
return a.second < b.second; // a.second가 더 작으면 true. 즉 작은게 앞에 배치가 된다.
}
sort(p.begin(), p.end(), compare);
\
§ my solution
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(pair<int, int> a, pair<int, int> b) {
if (a.second == b.second)
return a.first < b.first; // a.first가 작으면 true. 즉 작은게 앞에 배치가 된다.
return a.second < b.second; // a.second가 더 작으면 true. 즉 작은게 앞에 배치가 된다.
}
int main() {
ios_base::sync_with_stdio(0);
int num; cin >> num;
vector< pair<int, int> > p;
for (int i = 0; i < num; i++) {
int n1, n2; cin >> n1 >> n2;
p.push_back(make_pair(n1, n2));
}
sort(p.begin(), p.end(), compare);
for (auto x:p) {
cout << x.first << " " << x.second << '\n';
}
}
'Algorithms > Coding Test' 카테고리의 다른 글
[Baekjoon/백준] 13241, 5347번: [Recursion] (C/C++) ★★☆ (0) | 2022.11.04 |
---|---|
[Baekjoon/백준] 11004번, 2751번, 11931번(C/C++) / (알게된 내용X) (0) | 2022.11.03 |
[Baekjoon/백준] 10867번: 중복 빼고 정렬하기(C/C++) (0) | 2022.11.03 |
[Baekjoon/백준] 11728번: 배열 합치기_merge(C/C++) / (알게된 점 多) (0) | 2022.11.03 |
[Baekjoon/백준] 2161번: 카드1_deque(C/C++) / (알게된 점X) (0) | 2022.11.02 |