코테/BOJ

백준 6198 [옥상 정원 꾸미기] 파이썬

동 캄 2025. 2. 19. 00:16
반응형

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

#백준 6198 옥상 정원 꾸미기
import sys
N=int(sys.stdin.readline().rstrip()) # N 입력 처리
buildings=[] #빌딩의 값을 저장할 스택 생성
cnt=0
ans=0
for i in range(N):
    curr_building=int(sys.stdin.readline()) #현재 비교할 빌딩 입력 처리
    if buildings: # 스택에 값이 있다면
        if buildings[-1]>curr_building: #스택 마지막 값(빌딩 높이) > 현재 비교할 값(빌딩 높이)
            buildings.append(curr_building) #스택에 추가
            cnt+=1 #스택 크기 1증가
        else:
            while buildings: #스택이 없다면 반복문 탈출
                if buildings[-1]>curr_building: #스택 마지막 값(빌딩 높이) > 현재 비교할 값(빌딩 높이)
                    buildings.append(curr_building) #스택에 추가
                    cnt+=1 #스택 크기 1증가
                    break
                else: #스택 마지막 값(빌딩 높이) <= 현재 비교할 값(빌딩 높이)이면
                    buildings.pop() #스택에서 pop
                    cnt-=1 #스택 크기 1감소
            if not buildings: #만약 스택에 값이 없다면
                buildings.append(curr_building) #스택에 추가
                cnt+=1 #스택 크기 1증가
    else: #스택에 값이 없다면
        buildings.append(curr_building) #스택에 추가
        cnt+=1
    ans+=(cnt-1)
    
print(ans)

계속 값을 가져오면서 스택을 관리한다.

스택의 마지막 값 > 비교할 값 이면 스택에 저장하고,

그렇지 않다면 스택의 마지막 값 > 비교할 값이 될때까지 스택을 비운다.

반응형