Skip to content

Commit 6ba1724

Browse files
yongjun-0903ing-eoking
authored andcommitted
[오늘의 알고리즘] 광고 삽입
1 parent 2b831c2 commit 6ba1724

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

yongjun-0903/광고 삽입.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import heapq
2+
3+
def solution(play_time, adv_time, logs):
4+
answer = ''
5+
count = 0
6+
if play_time == adv_time:
7+
return "00:00:00"
8+
else:
9+
events = []
10+
11+
# 각 구간의 시작과 끝을 초 단위로 변환하여 이벤트로 추가
12+
for log in logs:
13+
interval_start, interval_end = log.split('-')
14+
15+
# 시작 시간을 초 단위로 변환
16+
start_hour, start_minute, start_second = map(int, interval_start.split(':'))
17+
start_time_in_seconds = start_hour * 3600 + start_minute * 60 + start_second
18+
events.append((start_time_in_seconds, 1)) # 시작점: +1
19+
20+
# 끝 시간을 초 단위로 변환
21+
end_hour, end_minute, end_second = map(int, interval_end.split(':'))
22+
end_time_in_seconds = end_hour * 3600 + end_minute * 60 + end_second
23+
events.append((end_time_in_seconds, -1)) # 끝점: -1
24+
25+
# 이벤트를 초 단위 시간으로 정렬
26+
events.sort(key=lambda x: (x[0], x[1])) # 시간이 같은 경우 끝점을 먼저 처리
27+
28+
# 라인 스위핑 기법을 통해 겹치는 구간을 추적
29+
current_overlap = 0
30+
max_overlap = 0
31+
max_start_time = None
32+
max_end_time = None
33+
34+
# 광고 삽입 가능한 시점 추적
35+
possible_ad_start_time = None
36+
37+
for time, event_type in events:
38+
# 구간이 시작되면 겹치는 구간 수 증가
39+
if event_type == 1:
40+
current_overlap += 1
41+
if current_overlap > max_overlap:
42+
# 가장 많은 겹침이 발생한 구간의 시작 시간 기록
43+
max_overlap = current_overlap
44+
max_start_time = time
45+
else:
46+
# 구간이 끝나면 겹치는 구간 수 감소
47+
if current_overlap == max_overlap:
48+
# 가장 많은 겹침이 발생한 구간의 끝 시간 기록
49+
max_end_time = time
50+
current_overlap -= 1
51+
52+
# 광고의 길이를 고려하여 가능한 시작 시점 계산
53+
possible_ad_start_time = max_start_time
54+
55+
# 광고가 겹치지 않게 하기 위해 광고가 시작될 수 있는 마지막 시간은
56+
ad_hour, ad_minute, ad_second = map(int, adv_time.split(':'))
57+
ad_duration = ad_hour * 3600 + ad_minute * 60 + ad_second
58+
ad_end_time = possible_ad_start_time + ad_duration
59+
60+
# 광고가 들어갈 수 있는 시간 범위가 구간과 겹치지 않도록 해야 합니다.
61+
for time, event_type in events:
62+
# 광고의 끝 시간이 구간의 시작 시간보다 뒤에 시작되거나 끝나야 한다.
63+
if time >= ad_end_time:
64+
# 광고가 삽입될 수 있는 시간 범위
65+
break
66+
possible_ad_start_time = time + ad_duration
67+
answer = ''
68+
hours = possible_ad_start_time // 3600
69+
minutes = (possible_ad_start_time % 3600) // 60
70+
seconds = possible_ad_start_time % 60
71+
answer = answer + str(hours) + ":" + str(minutes) + ":" + str(seconds)
72+
return answer
73+

0 commit comments

Comments
 (0)