본문 바로가기

알고리즘/백준

[백준] 2457번 : 공주님의 정원

728x90

2457번: 공주님의 정원

 

2457번: 공주님의 정원

첫째 줄에는 꽃들의 총 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 각 꽃이 피는 날짜와 지는 날짜가 주어진다. 하나의 날짜는 월과 일을 나타내는 두 숫자로 표현된다. 예를 들어서,

www.acmicpc.net

🤔 문제분석

시작날짜, 끝나는 날짜 오름차순으로 정렬하여 순회하면서, 현재의 시작시간에서 다음의 가장 끝나는시간이 긴 날짜를 선택하여 문제를 해결 할 수 있다.

두개의 케이스로 문제를 해결하였는데 배열을 순회하는 방식과, 스택을 활용하는 방식 두가지로 문제를 해결하였다.

두가지 모두 현재의 시작 날짜에서 가장 늦게 끝나는 날짜를 선택하는 해야한다.

💻 코드

배열 순회 방식

import sys
input = sys.stdin.readline
START_CONDITION = 301
END_CONDITION = 1201

N = int(input())
flower = []

for i in range(N):
    s_month, s_day, e_month, e_day = map(int, input().split())
    flower.append((s_month*100 + s_day, e_month*100 + e_day))

flower.sort()
end_date = START_CONDITION
count = 0

while flower:
    if flower[0][0] > end_date or end_date >= END_CONDITION:
        break
    
    max_end_date = -1
    
    for _ in range(len(flower)):
        if (flower[0][0] <= end_date):
            if (max_end_date <= flower[0][1]):
                max_end_date = flower[0][1]

            flower.remove(flower[0])
        else:
            break
        
    end_date = max_end_date
    count += 1
    
if end_date < END_CONDITION:
    print(0)
else:
    print(count)

스택

import sys
input = sys.stdin.readline
START_CONDITION = 301
END_CONDITION = 1201

N = int(input())
flower = []

for i in range(N):
    s_month, s_day, e_month, e_day = map(int, input().split())
    flower.append((s_month*100 + s_day, e_month*100 + e_day))

flower.sort(key=lambda x:(-x[0], -x[1]))
end_date = START_CONDITION
count = 0

while flower:
    if flower[-1][0] > end_date or end_date >= END_CONDITION:
        break
    
    max_end_date = -1
    while flower and flower[-1][0] <= end_date:
        max_end_date = max(flower[-1][1], max_end_date)
        flower.pop()
    
    count += 1
    end_date = max_end_date

if end_date < END_CONDITION:
    print(0)
else:
    print(count)

🎯 피드백 및 개선사항

문제의 포인트는 현재의 시작 날짜에서 가장 늦게 끝나는 날짜를 선택하는 해야한다.

728x90

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 1461번 : 도서관  (1) 2024.02.11
[백준] 13904번 : 과제  (1) 2024.02.10
[백준] 8980번 : 택배  (1) 2024.02.10
[백준] 7453번 : 합이 0인 네 정수  (1) 2024.02.10
[백준] 1253번 : 좋다  (1) 2024.02.10