본문 바로가기

PS/BOJ

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

문제

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

 

11651번: 좌표 정렬하기 2

첫째 줄에 점의 개수 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.second >> i.first;
  }
  sort(v.begin(), v.end());

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

pair<int, int>의 기본 정렬 방법은
first가 같으면 second가 증가하는 순으로 → first가 증가하는 순으로 인데
이 문제에서는 반대로 되어있으므로 first와 second의 순서를 바꿔 입력받고 바꿔 출력하면 된다.

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

using namespace std;

struct Pos {
  int x, y;

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

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;
}
설명

직접 비교 함수를 구현할 수도 있다.