[C++] 백준 11651번 좌표 정렬하기 2

xyzw·2025년 8월 23일
0

algorithm

목록 보기
68/97

https://www.acmicpc.net/problem/11651

풀이

sort 함수를 사용할 때 직접 정렬 기준을 지정하는 방식으로 풀었다.

기준을 직접 만들 때는 bool comp() 함수를 작성하면 된다.

코드

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef pair<int, int> pi;

bool comp(pi a, pi b) {
    if(a.second == b.second) return a.first < b.first;
    return a.second < b.second;
}

int main()
{
    int N;
    vector<pi> coord;
    
    cin >> N;
    for(int i=0; i<N; i++) {
        int x, y;
        cin >> x >> y;
        coord.push_back({x, y});
    }
    
    sort(coord.begin(), coord.end(), comp);
    
    for(int i=0; i<N; i++) {
        cout << coord[i].first << " " << coord[i].second << "\n";
    }
    
    return 0;
}

0개의 댓글