본문 바로가기

PS/BOJ

[C++] BOJ (백준) 11650 : 좌표 정렬하기

문제

11650번: 좌표 정렬하기 (acmicpc.net)

 

11650번: 좌표 정렬하기

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

www.acmicpc.net

코드 1 (std::pair)
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  cin >> n;
  vector<pair<int, int>> v(n);
  for (auto &i: v) {
    cin >> i.first >> i.second;
  }
  sort(v.begin(), v.end());

  for (auto i: v) {
    cout << i.first << ' ' << i.second << '\n';
  }
  return 0;
}
설명

sort 함수는 비교 함수를 명시하지 않으면 오름차순으로 정렬하는데,
pair<int, int>의 경우 첫번째 요소가 증가하는 순으로, 같으면 두번째 요소가 증가하는 순으로 정렬한다.

코드 2 (struct)
#include <iostream>
#include <algorithm>

using namespace std;

struct Pos {
  int x, y;

  bool operator<(const Pos &other) const {
    if (x == other.x) return y < other.y;
    return x < other.x;
  }
};

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  cin >> n;
  vector<Pos> v(n);
  for (auto &i: v) {
    cin >> i.x >> i.y;
  }
  sort(v.begin(), v.end());

  for (auto i: v) {
    cout << i.x << ' ' << i.y << '\n';
  }
  return 0;
}
설명

직접 비교 함수를 만들 수도 있다.