Programming/python
[Daily 코테] 백준 11650번: 좌표 정렬하기
mariej
2023. 10. 2. 13:23
https://www.acmicpc.net/problem/11650
11650번: 좌표 정렬하기
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
www.acmicpc.net
First Try
n = int(input())
coor = []
for _ in range(n):
x = int(input())
y = int(input())
coor.append((x, y))
coor = sorted(coor)
for i in range(n):
print(f"{coor[i][0]} {coor[i][1]}")
에러 원인: 좌표를 입력받을 때, 하나의 좌표가 한 줄에 입력되므로 x와 y를 따로 입력받으면 에러가 난다. 즉, 위 코드는 x에 "1 4" 를 동시에 입력받게 되는 것이다. (원래 목표대로라면 x에 1이, y에 4가 입력되어야한다.) 심지어 "1 4"는 string이므로 에러가 발생할 수밖에 없다.
Second Try
n = int(input())
coor = []
for _ in range(n):
x,y = int(input().split())
coor.append((x, y))
coor = sorted(coor)
for i in range(n):
print(f"{coor[i][0]} {coor[i][1]}")
에러 원인: input().split()의 출력값은 list형태이다. 이 list를 int함수로 씌워줬기 때문에 에러가 발생했다.
Third Try🎉
n = int(input())
coor = [] # 좌표들을 저장할 리스트를 정의한다.
for _ in range(n):
x,y = input().split() # 좌표들을 입력받을 때, 공백을 기준으로 x와 y로 분류하여 저장한다.
coor.append((int(x), int(y))) # 입력받은 x와 y를 하나의 집합으로 리스트에 추가한다.
coor = sorted(coor) # 리스트를 정렬하면, 문제의 조건에 맞게 x 기준으로 먼저 정렬 후 y순으로 정렬된다.
for i in range(n):
print(f"{coor[i][0]} {coor[i][1]}")