N = int(input())
candidate = []
for i in range(N):
height,weight = map(int,input().split())
candidate.append((height,weight))
candidate.sort() #튜플의 첫번째 원소인 '키' 순으로 정렬
h_best=0
last_weight=0
cnt = 0
for height,weight in candidate:
if height > h_best:
cnt+=1
h_best = height # 183
last_weight=weight #65
elif weight > last_weight:
cnt+=1
last_weight=weight
print(cnt)
>> 처음에는, 키에 대한 sort를 해놓고도, for문을 복잡하게 키,몸무게에 대해서 접근하다가 중도포기했다
N = int(input())
candidate = []
for i in range(N):
height,weight = map(int,input().split())
candidate.append((height,weight))
candidate.sort() #튜플의 첫번째 원소인 '키' 순으로 정렬
max_w = 0
cnt=0
for weight in candidate:
if (weight > max_w):
cnt += 1
max_w = weight
print(cnt)
>> 설명을 들은 후, 다시 적어본 코드이다. c++과 다른 파이썬 문법에서 오류가 났고, 튜플을 for문으로 접근할 때 헷갈렸다.
[잘못 생각한 부분]
1. sort()는 오름차순 기준이다. 나는 키가 큰사람 -> 작은 사람으로 정렬해야 하므로, 내림차순으로 sort를 해야한다
: sort(reverse = True)로 수정해야함.
2. 파이썬은 == 연산자가 아니라, =연산자이다. c++처럼 ==을 썼다가 오류났다.
3. 정답 + 해설
N = int(input())
candidate = []
for i in range(N):
height,weight = map(int,input().split())
candidate.append((height,weight))
candidate.sort(reverse=True) #내림차순 정렬 #튜플의 첫번째 원소인 '키' 순으로 정렬
max=0
cnt=0
for height,weight in candidate:
if weight>max:
cnt += 1
max= weight
print(cnt)
4. 새로 알게된 내용
튜플을 for문으로 접근할 때, 뒷쪽 요소만 접근하더라도 for x,y in tuple 이런 형식은 지켜줘야한다.
for문이 만능은 아니다. 시간복잡도도 매우 커질 수 있고, 내가 그래왔든 중도포기하기 쉽다.
최대값 =0 으로 초기화해놓고, 비교하면서 최대값을 가장 최신 컸던값으로 초기화하는 알고리즘이 생각보다 많이 사용된다. 꼭 기억해두자!!!