만족은 하되 안주하지는 말자

기록해야 기억한다

프로그래밍/programmers&bj

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

D36choi 2020. 7. 31. 21:49
728x90

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

 

11651번: 좌표 정렬하기 2

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

www.acmicpc.net

 

정렬하기류의 문제이다.

C++에서는 "algorithm" 헤더에 포함된 sort() 함수를 사용하여 풀 수 있다.

 

sort() 의 3번째 parameter 는 return type bool 의 함수로 정렬을 판단한다.

디폴트는 오름차순이다. 이 문제는 커스터마이징한 비교 함수를 만들어 풀었다.

 

#include <iostream>
#include <vector>
#include <algorithm>
#define PrintDots(i) cout << i.first << " " << i.second << "\n";
using namespace std;

bool comp(pair <int,int> dot1, pair <int,int> dot2) {
    if (dot1.second == dot2.second)
    {
        return dot1.first < dot2.first;
    }
    else
    {
        return dot1.second < dot2.second;
    }
}

int main()
{
    vector<pair<int,int>> dots;
    int N,x,y;
    cin >> N;
    for(int i=0; i<N; i++)
    {
        cin >> x >> y;
        dots.push_back({x,y});
    }
    sort(dots.begin(),dots.end(),comp);
    for(auto i : dots)
    {
        PrintDots(i);
    }
    return 0;
}

중요한 내용

sort함수의 compare 함수를 직접 만드는 법

pair 객체는 {..} 로 쉽게 만들수 있다.

'프로그래밍 > programmers&bj' 카테고리의 다른 글

[python] 백준 1902번: 수 찾기  (0) 2020.08.06
[C++] 백준 1309번: 동물원  (0) 2020.08.04
[C++] 백준 10953번: A+B - 6  (0) 2020.07.30
[C++] 백준 10951번: A+B - 4  (0) 2020.07.30
[C++] 백준 4963번: 섬의 개수  (0) 2020.07.21