컴굥일지

[BOJ/백준 11651][C++] 좌표 정렬하기 2 본문

알고리즘/코테 문제

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

gyong 2022. 5. 3. 01:58
반응형

문제

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

백준 11651

 

문제 내용

(x, y) 좌표를 입력받아, y좌표를 증가하는 순으로 정렬한다.

만약, y좌표가 같을 경우, x좌표가 증가하는 순으로 정렬하면 된다.

 

문제 풀이

pair<int,int>로 입력받아서 sort로 정렬한다.

sort로 정렬을 할 때에, 3번째 인자로 compare 함수를 구현하여 넣어준다.

 

코드

#include <iostream>
#include <algorithm> 
#include <vector>
using namespace std;

bool compare(pair<int, int>a, pair<int, int>b) {
	if (a.second == b.second) {
		return a.first < b.first;
	}
	else {
		return a.second < b.second;
	}
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	//입력
	int n;	cin >> n;
	vector<pair<int, int>> arr;

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

	//정렬
	sort(arr.begin(), arr.end(),compare);

	//출력
	for (int i = 0; i < n; i++) {
		cout << arr[i].first << ' ' << arr[i].second << '\n';
	}
}

반응형
Comments