isPowerfulBlog

[Solved] BOJ: 11651 | 좌표 정렬하기 2 본문

Algorithm

[Solved] BOJ: 11651 | 좌표 정렬하기 2

왕밤빵도라에몽 2022. 11. 11. 02:22

문제

y좌표 오름차순으로 좌표 정렬
y좌표가 같을 시, x 오름차순으로 좌표 정렬

입력과 출력

입력

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

출력

첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.


문제 해결 요약

x 먼저 정렬하고
y 정렬

코드 설명

import 및 입력받기

좌표 정보 입력

-

import sys
input = sys.stdin.readline
import heapq

n = int(input())
heap = []
for _ in range(n):
    x, y = map(int, input().split())
    heapq.heappush(heap, (x, y))
  • heapq에 좌표를 push해서
  • x min heap 만들기

x 오름차순 정렬

heap 요소들을 pop해서 x 오름차순 정렬을 한다.

-

x_sorted = []
while heap:
    tmp = heapq.heappop(heap)
    x_sorted.append((tmp[0], tmp[1]))

x_sorted.sort(key=lambda x:x[1])
  • heap이 빌 때까지 pop해서
  • 리스트에 append 해주면
  • x 오름차순 정렬된 리스트가 된다.

y 오름차순 정렬

y 기준 오름차순 정렬을 해준다.

-

x_sorted.sort(key=lambda x:x[1])
  • lambda 함수를 이용해 y 기준 오름차순 정렬을 한다.

전체 코드

import sys
input = sys.stdin.readline
import heapq

n = int(input())
heap = []
for _ in range(n):
    x, y = map(int, input().split())
    heapq.heappush(heap, (x, y))

x_sorted = []
while heap:
    tmp = heapq.heappop(heap)
    x_sorted.append((tmp[0], tmp[1]))

x_sorted.sort(key=lambda x:x[1])

for x in x_sorted:
    print(x[0], x[1])