• toc {:toc}

문제 확인하기

풀이

sort 함수의 compare를 어떻게 조절하는가에 대한 문제이다. 두 개의 쌍일 경우 pair, 3개의 쌍일 경우에는 tuple을 사용해서 풀이한다.

두 문제에서 다른 조건은 첫 번째 숫자를 먼저 비교하는가, 두 번째 숫자를 먼저 비교하는가에 대한 것이다. 때문에 compare 함수에서 차이를 두어 풀이한다. < 인 경우 오름차순으로 정렬, > 인 경우 내림차순으로 정렬한다.

#include <bits/stdc++.h>
using namespace std;
vector <pair<int, int>> vec;
 
bool compare(const pair<int, int> &a, const pair<int, int> &b){
    if (a.first == b.first){
        return a.second < b.second;
    }
    else{
        return a.first < b.first;
    }
}
 
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
 
    int n, x, y;
 
    cin >> n;
 
    for(int i=0; i<n; i++){
        cin >> x >> y;
        vec.push_back({x, y});
    }
    sort(vec.begin(), vec.end(), compare);
 
    for(int i=0; i<n; i++){
        cout << vec[i].first << " " << vec[i].second << '\n';
    }
 
    return 0;
}
#include <bits/stdc++.h>
using namespace std;
vector <pair<int, int>> vec;
 
bool compare(const pair<int, int> &a, const pair<int, int> &b){
    if (a.second == b.second){
        return a.first < b.first;
    }
    else{
        return a.second < b.second;
    }
}
 
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
 
    int n, x, y;
 
    cin >> n;
 
    for(int i=0; i<n; i++){
        cin >> x >> y;
        vec.push_back({x, y});
    }
    sort(vec.begin(), vec.end(), compare);
 
    for(int i=0; i<n; i++){
        cout << vec[i].first << " " << vec[i].second << '\n';
    }
 
    return 0;
}