Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
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
Archives
Today
Total
관리 메뉴

hwooo

프로그래머스 (C/C++, Java) 77486 : 다단계 칫솔 판매 본문

Study/Algorithm

프로그래머스 (C/C++, Java) 77486 : 다단계 칫솔 판매

hwooo 2025. 1. 13. 20:44

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

 

프로그래머스

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

programmers.co.kr

 

풀이

처음에는 amount 값을 한 번에 정리하고, 구조도의 제일 밑 부분부터 확인하며 income 값을 갱신해줬다.

그렇게 하니까 답이 나오지 않아 힌트를 봤고, 10씩 10번을 팔았을 때의 값을 10번 처리해주는 것과 100을 한 번에 처리해주는 것이 다른 결과값이 나오는 것을 알았고, 코드를 수정했다.

 

먼저 String 값을 인덱스로 사용하기 위해 map으로 설정했다. 한 번 팔 때부터 순회하며 해당 셀러가 소개받은 사람과 수익을 나눈다. 소개받은 사람을 현재 셀러로 지정하여 구성도의 최상단이 나올 때까지 작업을 반복하며 수익을 갱신한다.


C/C++ 코드

#include <string>
#include <vector>
#include <map>

using namespace std;

vector<int> solution(vector<string> enroll, vector<string> referral, vector<string> seller, vector<int> amount) {
    vector<int> income;
    map<string, int> seq;
    
    for (int i = 0; i < enroll.size(); i++) {
        seq[enroll[i]] = i;
        income.push_back(0);
    }
    
    for (int i = 0; i < seller.size(); i++) {
        string nowSeller = seller[i];
        int nowIncome = amount[i] * 100;
        income[seq[nowSeller]] += nowIncome;
        
        while (nowSeller != "-" && nowIncome) {
            string getSeller = referral[seq[nowSeller]];
            
            nowIncome /= 10;
            if (getSeller != "-")
                income[seq[getSeller]] += nowIncome;
            income[seq[nowSeller]] -= nowIncome;
            
            nowSeller = getSeller;
        }
    }
    return income;
}

 

Java 코드

import java.util.*;

class Solution {
    public int[] solution(String[] enroll, String[] referral, String[] seller, int[] amount) {
        HashMap <String, Integer> sequences = new HashMap<>();
        int[] income = new int[enroll.length];
        
        // 판매책의 조직 구성원 이름 - 순서쌍 저장
        for (int i = 0; i < enroll.length; i++) 
            sequences.put(enroll[i], i);
        
        for (int i = 0; i < seller.length; i++) {
            int nowIncome = amount[i] * 100;
            String nowSeller = seller[i];

            income[sequences.get(nowSeller)] += nowIncome;            
            while (!nowSeller.equals("-") && nowIncome > 0) {
                String nowGetter = referral[sequences.get(nowSeller)];
                
                nowIncome /= 10;
                if (!"-".equals(nowGetter))
                    income[sequences.get(nowGetter)] += nowIncome;                
                income[sequences.get(nowSeller)] -= nowIncome;

                nowSeller = nowGetter;
            }
        }
        
        return income;
    }
}