감자는 아직 꿈을 꾼다.

[프로그래머스] Lv.3 다단계 칫솔 판매 본문

코테적 감자/프로그래머스

[프로그래머스] Lv.3 다단계 칫솔 판매

dreaming-potato 2024. 11. 5. 21:23

알고리즘 : 트리 구조 떠올리기

별다른 알고리즘 보단 간단한 아이디어 문제 같다.


문제 설명

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

 

 

내 풀이

가장 단순한 풀이가 아닐까 생각한다.
우선 처음에는 부모와 자식노드들의 리스트로 클래스를 구성하여 구현할 생각이였으나,
결국 판매액을 구한 다음, 자신의 추천인(부모)에게 수수료를 제공하는 방식으로 진행됨 생각해
단순하게 부모 만 저장하는 HashMap을 만들어서 활용했다.
결국 루트인 민수한테 가는 것까지 고려서 10프로만 먹는 구조이기에
while문으로 부모가 민수의 부모일 경우에 탈출하는 조건으로 구성하여 간단히 풀이했다,

처음에 부모 정보를 저장하면서, 민수의 정보도 저장했다.
그리고 각 이름과 돈을 미리 0으로 세팅했고(돈 못벌었을경우 0원이기에)

끝이다.
간단한 구현 문제다.


import java.util.*;
class Solution {
    public int[] solution(String[] enroll, String[] referral, String[] seller, int[] amount) {
        HashMap<String,String> parents = new HashMap<>();
        parents.put("-","end");
        // 부모 정보 저장
        for (int i = 0; i< enroll.length;i++){
            parents.put(enroll[i],referral[i]);
        }

        // 이름과 돈 저장
        HashMap<String,Integer> moneys = new HashMap<>();
        for (String s : enroll){
            moneys.put(s,0);
        }
        moneys.put("-",0);
        for ( int i = 0 ; i < seller.length;i++){
            String s  = seller[i];
            int total = amount[i] * 100;

            while(!"end".equals(parents.get(s))){
                int yours = total / 10;
                int mine = total - yours;
                if (yours < 1) {
                    mine = total;
                }
                moneys.put(s,moneys.get(s) + mine);
                if (yours < 1){
                    break;
                }
                s = parents.get(s);
                total = yours;
            }
        }

        int[] answer = new int[enroll.length];
        int idx=  0;
        for (String s : enroll){
            answer[idx] = moneys.get(s);
            idx++;
        }

        return answer;
    }
}