📚 1. 그리디 정리
📖 A. 그리디
- 현재 상황에서 가장 좋아 보이는 것만을 선택하는 알고리즘
- '현재 상황에서 특정한 기준에 따라 가장 좋아 보이는 것만을 선택' 해서 최적의 해를 구해야한다.
- 코딩 테스트에서는 대부분 '최적의 해'를 찾는 문제가 출제되기 때문에 그리디 알고리즘의 정당성을 고민하면서 문제 해결 방안을 떠올려야 한다.
- 거스름돈 문제와 같이 자연수 N이 1이 될때까지 최소 몇 번을 수행해야 하는지 계산
- 다익스트라 최단 경로 알고리즘, 크루스칼 알고리즘은 모두 그리디 알고리즘이다.
📚 2. 문제
📖 Q 1 모험가 길드
n = int(input())
list_data = []
list_data = list(map(int,input().split()))
list_data.sort()
last_data = list_data[n-1]
total_cnt = 0
for idx in range(1,last_data+1):
if list_data.count(idx) >= idx:
total_cnt += 1
print(total_cnt)
📖 Q 2 곱하기 혹은 더하기
s = input()
list_data = list(s)
check_cal = False
result = 1
list_data.sort()
print(list_data)
for idx in range(len(list_data)):
if list_data[idx] == '0':
continue
if check_cal == False and list_data[idx] == '1':
result += 1
else:
check_cal = True
result *= int(list_data[idx])
print(result)
📖 Q 3 문자열 뒤집기
s = input()
before = 0
cnt_0 = 0
cnt_1 = 0
for idx in range(1, len(s)):
if s[before] != s[idx] and s[before] == '0':
cnt_0 += 1
before = idx
elif s[before] != s[idx] and s[before] == '1':
cnt_1 += 1
before = idx
if s[len(s)-1] == '0':
cnt_0 += 1
else:
cnt_1 += 1
if cnt_0 > cnt_1 :
print(cnt_1)
else:
print(cnt_0)
📖 4. 만들 수 없는 금액
n = int(input())
data = list(map(int,input().split()))
data.sort()
target = 1
for x in data:
if target < x:
break
target += x
print(target)
📖 5. 볼링공 고르기
n, m = map(int,input().split())
datalist = list(map(int,input().split()))
array = [0] * 11
for x in datalist:
array[x] += 1
result = 0
for i in range(1, m + 1):
n -= array[i]
result += array[i] * n
print(result)
📖 6. 무지의 먹방 라이브
import heapq
def solution(food_times, k):
if sum(food_times) <= k:
return -1
print(food_times)
q = []
for i in range(len(food_times)):
heapq.heappush(q, (food_times[i], i + 1))
sum_value = 0
previous = 0
length = len(food_times)
print(q)
while sum_value + ((q[0][0] - previous) * length) <= k:
now = heapq.heappop(q)[0]
sum_value += (now - previous) * length
length -= 1
previous = now
print(q)
result = sorted(q, key=lambda x: x[1])
print(result)
return result[(k - sum_value) % length][1]
print(solution([3, 1, 2,4], 5))