티스토리 뷰

 

프로그래머스

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

programmers.co.kr

 

# 핵심

문제를 잘 읽자

 

 

문제가 꽤 길어서 혼을 쏙 빼놓는데, 난이도는 그렇게 어려운 편은 아니었다.

판매원 클래스를 하나 따로 만들어서 자기 조상을 참조하도록 해놓고 이를 쭉 타고타고 올라가면서 수익금을 분배하면 된다. 

더이상 분배할 수익금이 없는 경우 / 조상이 더이상 없는 경우의 예외 케이스만 추가로 고려해주면 된다

 

 

# 더 이상 분배할 수익금이 없는 경우

분배금은 90%는 내가 갖고, 10%를 조상에게 떼주면 되는데.

내가 가질 금액: Math.ceil(profit * 0.9) <-- "올림"

조상에게 줄 금액: profit * 0.1

 

올림을 해준 이유는 원단위 절사를 해주기 위함!

내가 가질 금액은 올리고, 조상이 가질 금액은 내려버리면 된다.

(내림은 그냥 double -> int 형변환 시 알아서 잘린다)

 

예제를 보면 조상이 2원을 받았을 때가 나오는데, 이 경우

내가 가질 금액: Math.ceil(2 * 0.9) = 2

조상이 가질 금액: 2 * 0.1 = 0.2 = 0

 

조상이 가질 금액이 0원이 되면 조상 타고 올라가는거 멈추고 break 하면 끝

 

# 조상이 더이상 없는 경우

Root 노드인 Center가 있는데, Center에 도착하면 남은 분배금을 다 먹도록 해주기만 하면 된다

parent.parent = null;

 

변수명이 썩 맘에 들지는 않는다 ㅋㅋ

 

 

# 통과 코드

import java.util.*;

class Solution {

    private static class Employee {
        String name;
        int totalProfit; // 총 소득
        Employee parent; // 내 추천인

        public Employee(String name, Employee parent) {
            this.name = name;
            this.parent = parent;
        }
    }
    
    public int[] solution(String[] enroll, String[] referral, String[] seller, int[] amount) {

        Map<String, Employee> employeeMap = new HashMap<>();
        Employee center = new Employee("center", null); // Root
        employeeMap.put("center", center);

        // init
        Employee employee;
        for(int i = 0; i < enroll.length; i++) {
            if(referral[i].equals("-")) { // 추천인 없음
                employee = new Employee(enroll[i], center);
            } else { // 추천인 있음
                employee = new Employee(enroll[i], employeeMap.get(referral[i]));
            }
            employeeMap.put(enroll[i], employee);
        }

        // sell
        for(int i = 0; i < seller.length; i++) {
            employee = employeeMap.get(seller[i]);
            int profit = 100 * amount[i];
            
            employee.totalProfit += Math.ceil(profit * 0.9); // 90%는 내가 가짐
            profit *= 0.1; // 10%만 넘겨준다
            
            Employee parent = employee.parent;
            
            // 넘겨줄 조상이 있고, 분배금이 1원 이상인 동안
            while(parent != null && profit > 0) {
                parent.totalProfit += Math.ceil(profit * 0.9); // 90%는 내가 먹고
                profit *= 0.1; // 10%를 넘겨준다
                
                // 남은 돈은 center가 다 먹는다
                if(parent.parent == null) { 
                    parent.totalProfit += profit;
                    break;
                }
                parent = parent.parent; // 조상 타고 올라가기
            }
        }

        int[] ans = new int[enroll.length];
        for(int i = 0; i < ans.length; i++) {
            ans[i] = employeeMap.get(enroll[i]).totalProfit;
        }
        return ans;
    }
}

코드가 뭔가 썩 이쁘지는 않다.

메서드로 좀 분리하면 괜찮아질 것 같은데 귀찮아;;

 

옛날에 자료구조 수업에서 연결리스트에 대해 배우면서 포인터로 노드 타고타고 넘어가는걸 많이 했었는데 그거 했던 기억이 간만에 새록새록 난다. 그땐 정말 어려웠는데 ㅎㅎ...

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함