백준 11650 좌표 정렬하기 C++
2023. 9. 23. 19:37ㆍ알고리즘문제 풀이/백준
문제
2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
출력
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
내 풀이
sort함수를 이용하여 정렬한다.
compare함수를 통해 어떻게 정렬할 것인지에 대한 기준을 설정한다.
#include<iostream>
#include<utility>
#include<vector>
#include<algorithm>
using namespace std;
bool compare(const pair<int,int> &a, const pair<int,int> &b) {
if (a.first != b.first)
return (a.first < b.first);
else
return (a.second < b.second);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
std::vector <pair <int, int>> coordinate;
int n;
int x, y;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x >> y;
coordinate.push_back(make_pair(x, y));
}
sort(coordinate.begin(), coordinate.end(), compare);
for (int i = 0; i < n; i++)
{
cout << coordinate[i].first << " "
<< coordinate[i].second << '\n';
}
return 0;
}'알고리즘문제 풀이 > 백준' 카테고리의 다른 글
| 백준 11654 아스키 코드 Python (0) | 2023.09.23 |
|---|---|
| 백준 11651 좌표 정렬하기 2 C++ (0) | 2023.09.23 |
| 백준 11404 플로이드 C++ (0) | 2023.09.23 |
| 백준 11399 ATM C++ (0) | 2023.09.23 |
| 백준 11365 !밀비 급일 Python (0) | 2023.09.23 |