programmers.co.kr/learn/courses/30/lessons/150368
카카오톡에서는 이모티콘을 무제한으로 사용할 수 있는 이모티콘 플러스 서비스 가입자 수를 늘리려고 합니다.
이를 위해 카카오톡에서는 이모티콘 할인 행사를 하는데, 목표는 다음과 같습니다.
이모티콘 플러스 서비스 가입자를 최대한 늘리는 것.
이모티콘 판매액을 최대한 늘리는 것.
1번 목표가 우선이며, 2번 목표가 그 다음입니다.
이모티콘 할인 행사는 다음과 같은 방식으로 진행됩니다.
n명의 카카오톡 사용자들에게 이모티콘 m개를 할인하여 판매합니다.
이모티콘마다 할인율은 다를 수 있으며, 할인율은 10%, 20%, 30%, 40% 중 하나로 설정됩니다.
카카오톡 사용자들은 다음과 같은 기준을 따라 이모티콘을 사거나, 이모티콘 플러스 서비스에 가입합니다.
각 사용자들은 자신의 기준에 따라 일정 비율 이상 할인하는 이모티콘을 모두 구매합니다.
각 사용자들은 자신의 기준에 따라 이모티콘 구매 비용의 합이 일정 가격 이상이 된다면, 이모티콘 구매를 모두 취소하고 이모티콘 플러스 서비스에 가입합니다.
카카오톡 사용자 n명의 구매 기준을 담은 2차원 정수 배열 users, 이모티콘 m개의 정가를 담은 1차원 정수 배열 emoticons가 주어집니다. 이때, 행사 목적을 최대한으로 달성했을 때의 이모티콘 플러스 서비스 가입 수와 이모티콘 매출액을 1차원 정수 배열에 담아 return 하도록 solution 함수를 완성해주세요.
문제에서 주어지는 users
의 길이가 최대 100, emoticons
의 길이가 최대 7, 할인율이 4개 밖에 없기 때문에 완전 탐색으로 해결할 수 있습니다.
할인율이 10%부터 40%까지 하나씩 확인해야 하므로 중복 순열로 emoticons
의 가격을 구해야합니다. C++로 풀이를 할 경우 백 트래킹을 이용해야하지만, 파이썬은 product
를 통해 중복 순열을 쉽게 구현할 수 있습니다.
중복 순열로 생성된 가격과 할인율을 비교해 이모티콘 플러스 서비스 가입자와 이모티콘 매출액을 계산하여 answer
에 갱신해 return합니다.
from itertools import product
def solution(users, emoticons):
answer = [-1, -1]
for emoticon_discounts in product([10, 20, 30, 40], repeat=len(emoticons)):
new_users = 0
total_cost = 0
for user in users:
buy_cost = 0
for i in range(len(emoticon_discounts)):
if emoticon_discounts[i] >= user[0]:
buy_cost += (emoticons[i] * (1 - emoticon_discounts[i] / 100))
if buy_cost >= user[1]:
new_users += 1
buy_cost = 0
total_cost += buy_cost
if answer[0] < new_users:
answer[0] = new_users
answer[1] = total_cost
elif answer[0] == new_users:
answer[1] = max(answer[1], total_cost)
return answer
const discount = [10, 20, 30, 40]
signedUser = -1
sellCost = -1
function calculateEmoticonCost(d, c){
return (1 - d / 100) * c
}
function backTracking(users, emoticons, emoticonDiscount){
if (emoticonDiscount.length == emoticons.length){
totalSigned = 0
totalCost = 0
for(let i = 0; i < users.length; i++){
tempCost = 0
for(let j = 0; j < emoticons.length; j++){
if(users[i][0] <= emoticonDiscount[j]){
tempCost += calculateEmoticonCost(emoticonDiscount[j], emoticons[j])
}
}
if (tempCost >= users[i][1]){
totalSigned++
}else{
totalCost += tempCost
}
}
if(totalSigned > signedUser){
signedUser = totalSigned
sellCost = totalCost
}else if(totalSigned == signedUser){
sellCost = Math.max(sellCost, totalCost)
}
return
}
for (let i = 0; i < discount.length; ++i) {
emoticonDiscount.push(discount[i])
backTracking(users, emoticons, emoticonDiscount)
emoticonDiscount.pop()
}
}
function solution(users, emoticons) {
var answer = [];
backTracking(users, emoticons, [])
answer.push(signedUser)
answer.push(sellCost)
return answer;
}
웬만하면 파이썬으로 풀길...