본문 바로가기

Algorithm Problems/정렬

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

문제

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


문제 요약

2차원 평면의 점 n개가 주어졌을 때, 정렬하여 출력한다.

 

< 정렬 방법 >

1. y좌표가 증가하는 순서로 정렬한다.

2. y좌표가 같다면 x좌표가 증가하는 순서로 정렬한다.


코드

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

using namespace std;

int n;

vector<tuple<int, int>> arr;

// 정렬 조건
bool compare(tuple<int, int> a, tuple<int, int> b) {
	if (get<1>(a) == get<1>(b)) {
		return get<0>(a) < get<0>(b);
	}
	return get<1>(a) < get<1>(b);
}

int main() {
	// 입력
	cin >> n;

	for (int i = 0; i < n; i++) {
		int x, y;
		cin >> x >> y;
		arr.push_back({ x,y });
	}

	// compare를 기준으로 arr 정렬
	sort(arr.begin(), arr.end(), compare);

	// 출력
	for (int i = 0; i < n; i++) {
		int x, y;
		tie(x, y) = arr[i];

		cout << x << " " << y << "\n";
	}

	return 0;
}

코드 설명

1. x, y좌표를 튜플로 감싸 arr 벡터에 저장한다. 

 

2. compare 함수와 sort 함수를 이용해 주어진 조건으로 arr를 정렬하고, 출력한다.


고찰

튜플 내 요소를 인덱스를 통해 접근할 때 필요한 get 함수에 대해 알아두자.

 

=> get<인덱스 번호>(튜플 변수 이름)