상세 컨텐츠

본문 제목

[프로그래머스] 172927. 광물 캐기| 그리디 | 파이썬, 소스코드, 정답

Coding Test/문제풀이

by yooputer 2023. 5. 4. 09:50

본문

https://school.programmers.co.kr/learn/courses/30/lessons/172927

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


문제 요약

다이아 곡괭이, 철 곡괭이, 돌 곡괭이로 광물(다이아, 철, 돌)을 캐야한다. 

한 곡괭이는 5개의 광물을 캔 후에 교체할 수 있다. 사용한 곡괭이는 다시 사용할 수 없다.

 

곡괭이로 광물을 캘 때 얻는 피로도는 다음과 같다.

 

적절한 곡괭이를 골라 광물을 캘 때 얻을 수 있는 최소한의 피로도를 구하라.


문제 조건

입력

  • picks : 주어진 곡괭이의 개수 배열
    • 다이아 곡괭이 개수, 철 곡괭이 개수, 돌곡괭이 개수순
  • minelars : 광물들의 순서 배열
    • 원소는 "diamond", "iron", "stone" 중 하나

 

 


시행착오

구현에 치중하다보니 코드가 장황해졌다...

더 효율적인 코드가 존재할텐데 시간이 없어서 패스


접근방법

  1. 캘 수 있는 광물들만 따로 배열에 모은다. 
  2. 한 곡괭이는 5개만 캘 수 있으므로 광물 5개씩 구역을 나눈다.
  3. 돌곡괭이로 캤을 때 피로도가 높은 구역먼저 좋은 곡괭이로 캔다.

소스코드

from math import ceil

def solution(picks, minerals):
    answer = 0
    able_minerals = [-1]*min(sum(picks)*5, ceil(len(minerals)/5)*5)
    num_of_sections = len(able_minerals)//5

    for i in range(min(len(able_minerals), len(minerals))):
        if minerals[i] == "diamond":
            able_minerals[i] = 1
        elif minerals[i] == "iron":
            able_minerals[i] = 2
        else:
            able_minerals[i] = 3

    for _ in range(num_of_sections+1):
        max_fatigue = 0
        max_fatigue_section_index = 0

        for i in range(num_of_sections):
            fatigue = 0
            for j in range(5):
                if able_minerals[i*5 + j] == 1:
                    fatigue += 25
                elif able_minerals[i*5 + j] == 2:
                    fatigue += 5
                elif able_minerals[i*5 + j] == 3:
                    fatigue += 1

            if fatigue > max_fatigue:
                max_fatigue = fatigue
                max_fatigue_section_index = i

        type_of_pick = 0
        if picks[0] > 0:
            type_of_pick = 1
            picks[0] -= 1
        elif picks[1] > 0:
            type_of_pick = 2
            picks[1] -= 1
        else:
            type_of_pick = 3
            picks[2] -= 1

        for i in range(max_fatigue_section_index*5, max_fatigue_section_index*5 + 5):
            if able_minerals[i] > 0:
                if type_of_pick == 1:
                    answer += 1
                elif type_of_pick == 2:
                    if able_minerals[i] == 1:
                        answer += 5
                    else:
                        answer += 1
                elif type_of_pick == 3:
                    if able_minerals[i] == 1:
                        answer += 25
                    elif able_minerals[i] == 2:
                        answer += 5
                    else:
                        answer += 1

                able_minerals[i] = -1

    return answer

 

 

관련글 더보기