기계를 구입하려 하는데 이 기계는 추가 부품을 장착할 수 있다. 추가 부품은 종류당 하나씩만 장착 가능하고, 모든 추가 부품은 동일한 가격을 가진다.
원래 기계의 가격과 성능, 추가 부품의 가격과 각 부품의 성능이 주어졌을 때, 추가 부품을 장착하여 얻을 수 있는 최대 가성비를 정수 부분까지 구하시오(가격 및 성능은 상대적인 값으로 수치화되어 주어진다).
e.g.)
원래 기계의 가격 : 10
원래 기계의 성능 : 150
추가 부품의 가격 : 3
추가 부품의 성능 : 각각 30, 70, 15, 40, 65
추가 부품을 장착하여 얻을 수 있는 최대 가성비 : 17.81... → 17
(성능이 70과 65인 부품을 장착하면 됨)
144개의 풀이가 있습니다.
orp = 10
org = 150
adp = 3
adg = [30, 70, 15, 40, 65]
adg.sort(reverse=True)
for i in adg :
if org / orp > ( org + i ) / ( orp + adp ) :
break
else : org += i ; orp += adp
print int( org / orp )
# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3)
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')
# 기계를 구입하려 하는데 이 기계는 추가 부품을 장착할 수 있다.
# 추가 부품은 종류당 하나씩만 장착 가능하고, 모든 추가 부품은 동일한 가격을 가진다.
# 원래 기계의 가격과 성능, 추가 부품의 가격과 각 부품의 성능이 주어졌을 때,
# 추가 부품을 장착하여 얻을 수 있는 최대 가성비를 정수 부분까지 구하시오.
# (가격 및 성능은 상대적인 값으로 수치화되어 주어진다)
# e.g.)
# 원래 기계의 가격 : 10
# 원래 기계의 성능 : 150
# 추가 부품의 가격 : 3
# 추가 부품의 성능 : 각각 30, 70, 15, 40, 65
# 추가 부품을 장착하여 얻을 수 있는 최대 가성비 : 17.81... → 17
# (성능이 70과 65인 부품을 장착하면 됨)
mashine_price = 10
mashine_performance = 150
part_price = 3
parts_performance = [30, 70, 15, 40, 65]
number_parts = len(parts_performance)
performance_rate = mashine_performance / mashine_price
best_rate = performance_rate
best_parts = []
print("원래 기계 가성비 :", performance_rate)
# 부품 조합 모두 점검
for x in range(2 ** number_parts):
combination = bin(x + 1)[2:].zfill(number_parts)
addparts_performance = mashine_performance
addparts_price = mashine_price
for i in range(number_parts):
if combination[i] == '1':
addparts_performance += parts_performance[i]
addparts_price += part_price
addparts_rate = addparts_performance / addparts_price
# print(combination, addparts_performance, addparts_price, addparts_rate)
if addparts_rate > best_rate:
best_parts = [[combination, addparts_performance, addparts_price, addparts_rate]]
best_rate = addparts_rate
elif addparts_rate == best_rate:
best_parts += [[combination, addparts_performance, addparts_price, addparts_rate]]
if len(best_parts) > 0:
for combination_number in range(len(best_parts)):
print("다음 부품을 추가하세요")
for i in range(number_parts):
# print(best_parts[combination_number][0][i], i)
if best_parts[combination_number][0][i] == '1':
print("-", i + 1, "부품 : 가성비", parts_performance[i])
print("총 성능 :", best_parts[combination_number][1])
print("총 가격 :", best_parts[combination_number][2])
print("총 가성비 :", best_parts[combination_number][3])
else:
print("부품을 추가하지 마십시오")
cost = 10
perform = 150
a_cost = 3
a_perform = [30, 70, 15, 40, 65]
'''
추가부품의 가격이 같으므로 성능이 높은 부품부터 차례대로
추가하면서 누적된 총성능과 총가격을 리스트로 저장하고
마지막에 가격대 성능비를 계산해서 최대값을 출력
'''
a_perform.sort(reverse=True)
total_perform = [perform] #누적 성능
total_cost = [cost] #누적 가격
for p in a_perform:
total_perform.append(total_perform[-1]+p)
total_cost.append(total_cost[-1]+a_cost)
print max(map(lambda (p,c):p/c,zip(total_perform,total_cost)))
A = 10 B = 150 C = [30,70,15,40,65]
C.sort(reverse=True)
for x in C: if B/A<x/3: A+=3 B+=x else:break print(int(B/A))
import java.util.Scanner;
public class Q094 {
public static void main(String[] args) {
int priceM = 10;
int performM = 150;
int ce = performM / priceM;
int priceP = 3;
int[] performP = { 30, 70, 15, 40, 65 };
int totalPrice = priceM;
int totalPerform = performM;
for (int i = 0; i < performP.length; i++) {
if (performP[i] > ce * priceP) {
totalPrice += priceP;
totalPerform += performP[i];
}
}
System.out.println("최대가성비 : " + totalPerform/totalPrice);
}
}
기계의 가성비보다 부족한 부품을 장착하는건 최대 가성비에 부합하지 않기 때문에, 기계의 가성비보다 부족한 부품은 걸러내고, 기계의 가성비보다 좋은 부품은 총 구입가격에 더하고, 총 성능에 더했습니다. 그리고 총 성능/총 가격 = 최대 가성비로 책정해서 만들어 봤습니다.
#include <iostream>
#include <set>
#include <functional>
using namespace std;
int main(int argc, const char * argv[]) {
int cost, perf, addon_cost, n;
cin >> cost >> perf >> addon_cost >> n;
set<int, greater<int>> parts_perf;
double eff = (double)perf / cost;
for (int i = 0; i < n; i++) {
int p;
cin >> p;
parts_perf.insert(p);
}
double max_eff = eff;
for (int p : parts_perf) {
cost += 3;
perf += p;
eff = (double)perf / cost;
if (max_eff < eff) {
max_eff = eff;
} else break;
}
cout << (int)max_eff << endl;
}
m_price = 10
m_performance = 150
cost_effectiveness = m_performance / m_price
a_performance = [30, 70, 15, 40, 65]
a_performance.sort(reverse=True)
for x in range(1,len(a_performance)+1):
cost_effectiveness_new = (m_performance + sum(a_performance[:x]))/(m_price + x * 3)
if cost_effectiveness_new <= cost_effectiveness:
break
cost_effectiveness = cost_effectiveness_new
print('Maximum Cost Effectiveness: %d' % cost_effectiveness)
#coding: CP949
machine = float(input('원래 기계의 성능:'))
machine_price = float(input('원래 기계의 가격:'))
extra = sorted(list(map(float,input('추가 부품의 성능:').split(" "))))
extra_price=float(input('추가 부품의 가격:'))
extra.reverse()
j = 0
Q = machine
P = machine_price
result=[Q/P]
while j <=len(extra)-1:
Q+=extra[j]
P+=extra_price
result.append(Q/P)
j+=1
print(int(max(result)))
파이썬 3.4
livescript 입니다.
p0 = 10
m0 = 150
p1 = 3
ms = [30 70 15 40 65].sort!reverse!
r0 = m0 / p0
for m1 in ms
r1 = (m0 + m1) / (p0 + p1)
if r0 < r1
[p0, m0, r0] = [p0+p1, m0+m1, r1]
else
console.log Math.floor r0
break
Python
price = 10
performence = 150
add_price = 3
add_performence = [30, 70, 15, 40, 65]
add_performence.sort(reverse=True)
for p in add_performence:
cost = performence / price
new_cost = (performence + p) / (price + add_price)
if cost > new_cost:
break;
else:
performence += p
price += add_price
print(performence // price)
파이썬으로 무식하게 풀었습니다
ori_price = 10
ori_perf = 150
ext_price = 3
ext_perf = [30,70,15,40,65]
ext_perf = sorted(ext_perf,reverse=True)
maxpp = ori_perf/float(ori_price)
for i in range(len(ext_perf)):
tmp_price = ori_price
tmp_perf = ori_perf
for mem in ext_perf[:i+1]:
tmp_price+=3
tmp_perf+=mem
if maxpp < tmp_perf/float(tmp_price):
maxpp = tmp_perf/float(tmp_price)
print "i = %d pp = %f"%(i,tmp_perf/float(tmp_price))
print maxpp
price = 10
abil = 150
part_price = 3
part_abil =[30,70,15,40,65]
for i in sorted(part_abil) :
print("%d 의 가성비 : %d"%(i,(abil+i)//price+part_price))
Python 3.5.2
import java.util.Arrays;
import java.util.Comparator;
public class test {
public static void main(String[] argv) {
int beforeAct = 150;
int beforeMoney = 10;
Integer addAct[] = {30, 70, 15, 40 ,65};
int addMoney = 3;
int resultAct = 0;
int resultMoney = 0;
double result = 0.0;
double tempResult = 0.0;
Arrays.sort(addAct, new CompartorSort());
for(int i = 0 ; i < addAct.length; i ++){
resultAct = 0;
resultMoney = 0;
for(int j = 0; j <= i; j ++){
resultAct += addAct[j];
resultMoney += addMoney;
}
tempResult = (double)(resultAct + beforeAct) / (double)(resultMoney + beforeMoney);
if(result < tempResult){
result = tempResult;
}
}
System.out.println("최대 가성비 : " + result);
System.out.println("최대 가성비(Int형) : " + (int)result);
}
}
class CompartorSort implements Comparator<Integer>{
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if(o1 > o2){
return -1;
}else if(o1 == o2){
return 0;
}else {
return 1;
}
}
}
Java
Ruby
최대 가성비는 3가지 중 하나. 기본 가성비(부품 가성비가 낮은 경우), 기본성능+가성비최고부품, 기본성능+여러부품
max_pf_with_options = ->part_pows, p_pows=part_pows.sort.reverse do
base_pow, base_price, p_price = 150, 10, 3
pf = ->size { (base_pow + p_pows[0,size].sum) / (base_price + p_price*size) }
(1..p_pows.size).reduce([base_pow/base_price]) {|pfs,size| pfs << pf[size]}.max
end
Test
expect( max_pf_with_options[ [30, 70, 15, 40, 65] ] ).to eq 17
Out
#=> max_pf_with_options[ [30, 70, 15, 40, 65] ]
17
파이썬 2.7 입니다 / 부품을 전부 부착하는 경우의 수는 2^5개 이지만, / 최대값을 구하는 문제이기 때문에 / 1개 부착할때 최대 가성비는 70 / 2개 부착할때 70, 65 / 3개 70, 65, 40 / ... / 이므로 5가지 경우만 비교하였습니다
A = 10
B = 150
C = 3
D = [30, 70, 15, 40, 65]
D.sort(reverse = True)
G = []
def g_sum(n): #부품이 n개일때 최대 성능
S = 0
for i in range(n+1):
S += D[i]
return S
for i in range(len(D)):
G.append( ( g_sum(i) + B ) / float( A + C*(i+1) ) )
G.sort(reverse = True)
print G[0]
답: 17.8125 // 순위: 70,65 > 70,65,40 > 70 > 70,65,40,30 > 전부다 사용
public class Ex14 { public int[] arraySort(int[] value){ for(int i = 0; i < value.length - 1; i++){ int temp = 0; for(int j = 0; j < value.length - 1; j++){ if(value[j] < value[j+1]) { temp = value[j]; value[j] = value[j+1]; value[j+1] = temp; } } } return value; }
public static void main(String[] args) {
int addPrice = 3;
int[] addAbility = {30, 70, 15, 40, 65};
Ex14 sort = new Ex14();
addAbility = sort.arraySort(addAbility);
double bestAbility = 0;
for(int i = 0; i < addAbility.length - 1; i++){
double ProductPrice = 10;
double ProductAbility = 150;
double Ability = 0;
for(int j = 0; j <= i; j++){
ProductPrice += addPrice;
ProductAbility += addAbility[j];
Ability = ProductAbility / ProductPrice;
}
if(bestAbility < Ability) {
bestAbility = Ability;
}
}
System.out.println("최대가성비 = " + bestAbility);
System.out.println("최대가성비(소수점버림) = " + (int)bestAbility);
}
}
'''
A/C < a/c
Ca > Ac
AC+Ca > AC+Ac
C(A+a) > A(C+c)
(A+a)/(C+c) > A/C
을(를) 통해
추가하려는 부품의 가성비가
이전에 기계와 부품들의 합에서 나온 가성비보다 크면
추가했을 때 더 큰 가성비가 나옴을 알 수 있고
추가부품의 가격은 고정되어 있으므로
추가부품의 성능이 훌륭한 순으로 정렬 후 그리디
'''
machine_price = 10
machine_pf = 150
part_price = 3
part_pf = [30, 70, 15, 40, 65]
sum_price = machine_price
sum_pf = machine_pf
part_pf.sort(reverse=True)
i = 0
while sum_pf/sum_price < part_pf[i]/part_price:
sum_price += part_price
sum_pf += part_pf[i]
i += 1
print sum_pf/sum_price
price=10
perform=150
add_price=3
add_perform=[30,70,15,40,65]
sum_price=price
sum_perform=perform
added_perform=[]
for p in add_perform:
if sum_perform / sum_price < (sum_perform + p) / (sum_price + add_price):
sum_perform+=p
sum_price+=add_price
added_perform.append(p)
print('성능이 %s인 부품을 장착할때 가성비:%d' % (added_perform, sum_perform / sum_price))
Python 3.5.2에서 작성하였습니다.
매트랩으로 작성되었습니다. 최고 가성비를 찾기위해서는 성능이 좋은 부품부터 설치하면 되므로 성능이 좋은 부품부터 추가하여 가성비를 구하고 그중에서 최고값을 찾는 방식으로 하였습니다.
org = 150;
orp = 10;
prt = [30, 70, 15, 40, 65];
prp = 3;
prt = sort(prt, 'descend'); % 성능이 좋은것부터 나열합니다.
for i = 1 : length(prt)
org = org + prt(1, i);
result(1, i) = (org)/(orp + i*prp);
end
fix(max(result))
price = int(input('원래 기계의 가격 : '))
perform = int(input('원래 기계의 성능 : '))
add_price = int(input('추가 부품의 가격 : '))
add_perform = sorted(list(map(int,input('추가 부품의 성능 : 각각 ').split(' '))),reverse=True)
X = [round((sum(add_perform[:x+1])+perform)/(price+add_price*(x+1)),2) for x in range(len(add_perform))]
print('추가 부품을 장착하여 얻을 수 있는 최대 가성비 : ','%.2f... →' % max(X), int(max(X)))
#### 2017.01.23 D-395 ####
def opti(n,N,p,data): #n:원래 기계가격, N:원래 기계성능, p:추가부품 가격, data:추가부품 성능
data.sort()
data.reverse()
s=0
while N/(n+3*s)<(N+data[0])/(n+3*s+3):
N+=data[0]
s+=1
data=data[1:]
if data==[]:
break
return int(N/(n+3*s))
import java.util.Arrays;
import java.util.Comparator;
public class CostEffectiveness {
public static void main(String[] args) {
Integer component[] = {30, 70, 15, 40, 65};
Double maxCostEffectiveness = 0D;
Integer price = 10;
Integer componentPrice = 3;
Integer performance = 150;
Arrays.sort(component, Comparator.comparing(Integer::intValue).reversed());
for (int i = 0; i < component.length; i++) {
performance = performance + component[i];
price = price + componentPrice;
Double costEffectiveness = Double.valueOf(performance) / Double.valueOf(price);
if (maxCostEffectiveness < costEffectiveness) {
maxCostEffectiveness = costEffectiveness;
}
}
System.out.println(maxCostEffectiveness);
}
}
MATLAB 입니다. O(2^N) 알고리즘이네요. N=14,16 정도까지는 돌아가는데, 그 이상 크기가 될수록 어마어마하게 느려집니다.
%% input
original_machine_price=10;
original_machine_performance=150;
additional_element_price=3;
additional_element_performance=[30,70,15,40,65];
%additional_element_performance=randi([20,100],1,18)
%% case 2^5=32
tic
additional_element_performance_len=length(additional_element_performance);
case_num=2^additional_element_performance_len;
current_best_ratio=original_machine_performance/original_machine_price;
best_arr=[];
for p=0:case_num-1
cur_val=p;
cur_arr=zeros(1,additional_element_performance_len);
for q=additional_element_performance_len-1:-1:0
if cur_val >= 2^q
cur_arr(q+1)=1;
cur_val=cur_val-2^q;
end
end
%disp([num2str(p) ' ' num2str(cur_arr)]);
if p==case_num-1
a=1;
end
cur_ratio=(original_machine_performance + sum(additional_element_performance(find(cur_arr)))) / (original_machine_price + 3*sum(cur_arr));
%disp([num2str(p) ' ' num2str(cur_arr) ' ' num2str(cur_ratio)]);
if cur_ratio > current_best_ratio
current_best_ratio=cur_ratio;
best_arr=cur_arr;
end
end
toc
disp([num2str(additional_element_performance(find(best_arr))) ' 선택했을 때 최고 가성비 ' num2str(current_best_ratio)]);
python 3.4.2
mc = 10
mp = 150
pc = 3
pp = [30,70,15,40,65]
revers_pp = list(reversed(sorted(pp)))
for i in revers_pp:
if mp/mc > (mp+i)/(mc+pc):
break
else:
mp += i
mc += pc
print(mp//mc)
#14.py
origin_price = 10
origin_abil = 150
add_price = 3
add_abil_lst = sorted([30,70,15,40,65])[::-1]
added = []
def get_eff(price, abil):
return int(abil/price)
for add_abil in add_abil_lst:
eff_now = get_eff(origin_price, origin_abil)
if eff_now < get_eff(origin_price+add_price, origin_abil+add_abil):
added.append(add_abil)
origin_price, origin_abil = origin_price + add_price, origin_abil + add_abil
else : break
print( added )
print(get_eff(origin_price, origin_abil))
OriPri = input("원래 기계의 가격 : ")
OriPer = input("원래 기계의 성능 : ")
AddPri = input("추가 부품의 가격 : ")
a = input("추가 부품의 성능 : 각각 ")
AddPer = [int(x) for x in a.split(', ')]
AddWor = [i/int(AddPri) for i in AddPer]
AddPer2 = []
for i in range(len(AddWor)):
if AddWor[i] >= int(OriPer) / int(OriPri):
AddPer2.append(AddPer[i])
TotPer = sum(AddPer2) + int(OriPer)
TotWor = int(TotPer / (int(OriPri) + int(AddPri) * len(AddPer2)))
print("추가 부품을 장착하여 얻을 수 있는 최대 가성비 : %d" % TotWor)
// 가성비 - C#
using System;
using System.Collections.Generic;
namespace EffectivePrice
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("기계를 샀습니다. 과연 어떤 추가 부품을 사야 가성비가 좋을까요?");
Console.Write("원래 기계의 가격:");
int initprice = int.Parse(Console.ReadLine());
Console.Write("원래 기계의 성능:");
int initpower = int.Parse(Console.ReadLine());
Console.Write("추가 부품의 가격:");
int addiprice = int.Parse(Console.ReadLine());
Console.Write("추가 부품의 성능:");
string addipower = Console.ReadLine();
List<int> eachpower = new List<int>();
for (int i = 0; true; i++)
{
try { eachpower.Add(int.Parse(addipower.Split(' ')[i])); }
catch { break; }
}
double maxeffect = 0;
foreach (int i in eachpower)
{
if (maxeffect < ((initpower + i) / (initprice + addiprice)))
maxeffect = ((initpower + i) / (initprice + addiprice));
}
Console.WriteLine("낼 수 있는 최대 가성비: {0}", (int)maxeffect);
}
}
}
tcost = 10
tperf = 150
cost = 3
cperf = [30, 70, 15, 40, 65]
cperf.sort()
while cperf:
perf = cperf.pop()
tmp = (tperf + perf) / (tcost + cost)
if tmp < tperf / tcost:
break
else:
tperf += perf
tcost += cost
print(int(tperf / tcost))
Python 3 으로 풀었습니다.
def max_cost_effect(origin_cost, origin_p, available_cost, available_ps):
basic_cost_effect = origin_p / origin_cost
min_ps = basic_cost_effect * available_cost
over_min_ps = [ p for p in available_ps if p > min_ps ]
return int((origin_p + sum(over_min_ps))
/ (origin_cost + available_cost * len(over_min_ps)))
import java.util.*;
public class GoodPrice {
public static void main(String[] args) {
int cost = 10;
int partscost = 3;
int perf = 150;
int[] partsperf = {30, 70, 15, 40, 65};
int max=0;
Arrays.sort(partsperf);
for(int i=partsperf.length-1; i>=0; i--) {
cost += partscost;
perf += partsperf[i];
if(max < perf/cost) max = perf/cost;
}
System.out.println(max);
}
}
int org_cost = 10;
int org_pef = 150;
int add_cost = 3;
int add_pef[] = { 30,70,15,40,65 };
for (int item : add_pef) {
if ((double)org_pef / org_cost < (double)(item+ org_pef) / (add_cost+ org_cost)) {
org_cost += add_cost;
org_pef += item;
}
}
cout << org_pef / org_cost << endl;
public static void main(String[] argv) {
//가성비 = 성능/가격
int orgMachinePrice = 10;
int orgPerformance = 150;
int partsPrice = 3;
Integer[] partsPerformance = {30, 70, 15, 40 ,65};;
int machinePrice = orgMachinePrice;
double costEffectiveness = orgPerformance / orgMachinePrice;
int len = partsPerformance.length;
Arrays.sort(partsPerformance, new Ascending());
for(int i = 0; i < len; i++) {
orgPerformance += partsPerformance[i];
machinePrice += partsPrice;
double temp = (double)orgPerformance / machinePrice;
if(costEffectiveness < temp) {
costEffectiveness = temp;
}
}
System.out.println((int)costEffectiveness);
}
static class Ascending implements Comparator {
public int compare(Object o1, Object o2) {
if(o1 instanceof Comparable && o2 instanceof Comparable) {
Comparable c1 = (Comparable)o1;
Comparable c2 = (Comparable)o2;
return c2.compareTo(c1);
}
return -1;
}
}
# python 3.6
import itertools as it
ov = 10
op = 150
av = 3
ap = [30, 70, 15, 40, 65]
max_coeff = 0
for sel_num in range(1, len(ap) + 1):
ap_gen = it.combinations(ap, sel_num)
rept = True
while rept:
try:
lst = next(ap_gen)
except StopIteration:
rept = False
else:
max_coeff = max(max_coeff, (sum(lst) + op) / (len(lst) * av + ov))
print(int(max_coeff))
cost = 10
perf = 150
partcost = 3
parts = [30, 70, 15, 40, 65]
parts.sort(reverse = True)
maxeff = perf / cost
for p in parts:
cost += partcost
perf += p
maxeff = max(maxeff, perf/cost)
print(int(maxeff))
python
def EFFI(E, base, count = 0):
E.sort(reverse = True)
for i in range(len(E)):
if (base + E[i])/(10+3*(i+1)) > base/(10+3*i):
base += E[i]
count += 1
effi = base / (10 + count*3)
print(int(effi))
EFFI([30, 70, 15, 40, 65], 150)
원래 가성비보다 추가부품의 가성비가 큰 것들만 뽑아서 구해주면 되니 어렵지 않네요ㅎㅎ
m_price = 10
m_perf = 150
a_price = 3
a_perf = [30, 70, 15, 40, 65]
cost_eff = m_perf/m_price
k = [x for x in a_perf if x/a_price > cost_eff]
for x in k:
m_perf+=x
m_price+=a_price
print(m_perf, m_price)
print(m_perf//m_price)
def tester(cost1, pows1, cost2, pows2):
tmpcost=cost1
tmppows=pows1
result=0
count=0
for i in pows2:
if result<=(tmppows+i)/(tmpcost+cost2):
tmppows+=i
tmpcost+=cost2
result=tmppows/tmpcost
count+=1
else: break
return(int(result), pows2[:count])
mcost, mpow=map(int, input('기계 가격, 기계 성능: ').split())
tmpp=list(map(int, input('부품 가격, 부품 성능1, 성능2, ...: ').split()))
pcost, ppow=tmpp.pop(0), sorted(tmpp, reverse=True)
ans=tester(mcost, mpow, pcost, ppow)
print('최대가성비: {};{}추가시'.format(ans[0], ans[1]))
public static void main(String[] args) {
int oriPrice = 10;
int oriPower = 150;
int addPrice = 3;
int addPower[] = {30,70,15,40,65};
ArrayList addPower2 = new ArrayList();
for(int i=0; i<addPower.length; i++)
{
addPower2.add(addPower[i]);
}
Collections.sort(addPower2);
Collections.reverse(addPower2);
int realAddPower = (int)addPower2.get(0);
int oriVal = oriPower/oriPrice;
int addVal = (oriPower+realAddPower)/(oriPrice+addPrice);
System.out.println("기존 성능 : "+oriVal);
System.out.println("이후 성능 : "+addVal);
}
파이썬 3.6
" 가능한 부품 조합 case를 모두 구하고 case별 가성비를 구하여 최대값을 산출 "
sub_effect = [30, 70 ,15, 40, 65]
sub_cost = 3
main_cost = 10
main_effect = 150
def effectiveness(sub_effect):
effects =[]
subs = []
sub_effect.sort()
print("\n")
for i in sub_effect:
subs.append([i])
n = len([i])
effects.append((main_effect+i) / (main_cost+sub_cost*n))
for j in sub_effect[1:]:
if i == j:
pass
else:
subs.append([i,j])
n = len([i,j])
effects.append((main_effect+i+j)/(main_cost + sub_cost*n))
for k in sub_effect[2:]:
if i == j or i == k or j == k:
pass
else:
subs.append([i,j,k])
n = len([i,j,k])
effects.append((main_effect+i+j+k)/(main_cost + sub_cost*n))
for l in sub_effect[3:]:
if i == j or i == k or i == l or j == k or j == l or k == l:
pass
else:
subs.append([i,j,k,l])
n = len([i,j,k,l])
effects.append((main_effect + i+j+k+l)/(main_cost + sub_cost*n))
for m in sub_effect[4:]:
if i == j or i == j or i == k or i == l or i == m or j == k or j == l or j == m or k == l or k == m or l == m:
pass
else:
subs.append([i,j,k,l,m])
n = len([i,j,k,l,m])
effects.append((main_effect+i+j+k+l+m)/(main_cost + sub_cost*n))
print(" ▶ 원기계의 성능 / 가격 = 가성비 : %d / %d = %d " %(main_cost, main_effect, main_effect/main_cost),"\n")
print(" ▶ 각 부품의 성능: ", sub_effect,"\n")
print(" ▶ 가성비가 가장 좋은 부품 조합: " ,subs[effects.index(max(effects))]," / 최대 가성비: %d " % int(max(effects)),"\n")
effectiveness(sub_effect)
▶ 원기계의 성능 / 가격 = 가성비 : 10 / 150 = 15
▶ 각 부품의 성능: [15, 30, 40, 65, 70]
▶ 가성비가 가장 좋은 부품 조합: [65, 70] / 최대 가성비: 17
자바
package cddj;
import java.util.*;
public class cddj12 {
public static void main(String[] args) {
long BP = 150;
long EFF = BP / 10;
String[] P = {"30", "70", "15", "40", "65"};
Arrays.sort(P, Collections.reverseOrder());
for (int i = 0; i < P.length; i++) {
BP = BP + Integer.valueOf(P[i]);
if (EFF < BP / (13 + 3*i)) {
EFF = BP / (13 + 3*i);
}
}
System.out.println(EFF);
}
}
input = 10
output = 150
result = 0
mat = [30, 70, 15, 40, 65]
mat.sort(reverse=True)
list = []
for i in mat:
input += 3
output += i
list.append(output/input)
for i in list:
if i>result:
result = i
print(int(result))
base_cost = 10
base_per = 150
parts = [30, 70, 15, 40, 65]
parts.sort()
parts.reverse()
gasungbi = []
for i in range(5):
gasungbi.append((base_per+sum(parts[:i]))/(10+3*i))
print(int(max(gasungbi)))
가격=10
성능=150
추가부품=[30,70,15,40,65]
추가부품.sort(reverse=True)
for x in 추가부품:
if 성능/가격<x/3:
가격+=3
성능+=x
else:break
print(int(성능/가격))
1위랑 똑같은 풀이입니다.
from itertools import combinations
add_part_price=[30,70,15,40,65]
full_performance=150
Max_efficiency=-99
for k in range(1,6):
temp_comb=combinations(add_part_price,k)
for g in temp_comb:
temp_sum=0
temp_sum+=sum(g)
temp_efficiency=(temp_sum+full_performance)/(10+3*k)
if temp_efficiency>Max_efficiency:
Max_efficiency=temp_efficiency
print(int(Max_efficiency))
def best_value():
pass
machine_price = int(input("원래 기계의 가격 : "))
machine_performance = int(input("원래 기계의 성능 : "))
machine_value = machine_performance / machine_price
part_price = int(input("추가 부품의 가격 : "))
part_performance = input("추가 부품의 성능 : ").split(",")
total_price = machine_price
total_performance = machine_performance
for part in part_performance:
if machine_value < int(part) / part_price:
total_price += part_price
total_performance += int(part)
total_value = int(total_performance / total_price)
print("추가 부품을 장착하여 얻을 수 있는 최대 가성비 : %d" % (total_value))
price=10
performance=150
pay=3
part_price=sorted([30,70,15,40,65])
result=[]
for i in range(len(part_price)):
performance += part_price.pop()
price += 3
result.append(performance/price)
print(int(max(result)))
초보가 몇줄적어봤는데....아참 최대일 때가 여러개인경우 중복계산하려면 대여섯줄 추가해야해서 뺐어요
from itertools import combinations
pc = int(input("Price : "))
pf = int(input("Performance : "))
pc_add = int(input("Price_add : "))
pf_add = list(map(int, input('Performance_add : ').split()))
temp = pf_add + [0, 0, 0, 0, 0]
temp_com = list(combinations(temp, 5))
rate = pf/pc
best_pf5 = 0
for pf5 in temp_com:
pf_rate = (pf + sum(pf5)) / (pc + pc_add * (5 - pf5.count(0)))
if pf_rate >= rate:
rate = pf_rate
best_pf5 = pf5
print(rate, best_pf5)
Swift입니다. 만들다 보니 Kim JungRae님 코드를 Swift로 포팅한거네요.
import Foundation
var orgPerformance:Double = 150
var orgPrice:Double = 10
var partPrice:Double = 3
var partPerformance:[Double] = [30, 70, 15, 40, 65]
partPerformance.sort(by: >)
for i in 0..<partPerformance.count {
if (orgPerformance / orgPrice) > (orgPerformance + partPerformance[i]) / (orgPrice + partPrice) {
break
} else {
orgPerformance += partPerformance[i]
orgPrice += partPrice
}
}
print(Int(orgPerformance / orgPrice))
ori_price = 10
ori_performance = 150
cost_effectiveness = ori_performance / ori_price
new_performance = [30,70,15,40,65]
new_performance.sort(reverse=True)
new_price = 3
sum_performance = 0
for i in range(len(new_performance)):
sum_performance += new_performance[i]
after_cost_effectiveness = (ori_performance + sum_performance) / (ori_price + (new_price * (i+1)))
if after_cost_effectiveness < cost_effectiveness :
break
else :
cost_effectiveness = after_cost_effectiveness
print(cost_effectiveness)
python 3.6.1
orig_cost = eval(input("the original cost of the machine: "))
orig_perf = eval(input("the extent of original performance of the machine: "))
add_cost = eval(input("the additional cost of the machine: "))
add_perf_input = input("the extents of additional performance of the machine, separating with ',': ").split(',')
add_perf = [eval(i) for i in add_perf_input]
while (orig_perf + max(add_perf))/(add_cost + orig_cost) > orig_perf/orig_cost:
orig_perf += max(add_perf)
orig_cost += add_cost
add_perf.remove(max(add_perf))
print(orig_perf//orig_cost)
package codingDojang;
public class InOutMax {
public String inOutMax(int oP, int oC, int addP, int[] addC) {
int result = 0;
int totalPrc = oP;
int totalCap = oC;
int CDP = totalPrc/totalCap;
String eachValue = "";
for(int i = 0; i < addC.length; i++) {
for(int j = i + 1; j < addC.length; j++) {
if(addC[i] < addC[j]) {
int temp = addC[i];
addC[i] = addC[j];
addC[j] = temp;
}
}
}
for(int i = 0; i < addC.length; i++) {
totalPrc += addP;
totalCap += addC[i];
if(CDP < totalCap/totalPrc) {
CDP = totalCap/totalPrc;
} else {
break;
}
if(eachValue !="") {
eachValue += ", " + addC[i];
} else {
eachValue += addC[i];
}
result = CDP;
}
return "가성비 최대값: " + result + " 추가부품: " + eachValue;
}
public static void main(String[] args) {
int oP = 10;
int oC = 150;
int addP = 3;
int[] addC = {30, 70, 15, 40, 65};
InOutMax iom = new InOutMax();
System.out.println(iom.inOutMax(oP, oC, addP, addC));
}
}
#include<iostream>
using namespace std;
int main()
{
int array[5] = { 30, 70, 15, 40, 65 };
int max = array[4] + array[0];
int tmp=0, max_first, max_second;
for (int i = 0; i < 5; i++)
{
for (int j = i+1; j < 5; j++)
{
tmp = array[i] + array[j];
if (max < tmp)
{
max = tmp;
max_first = array[i];
max_second = array[j];
}
}
}
cout << "최대 가성비는" << max_first << ' ' << max_second << endl;
}
oripri=10
oriper=150
addpri=3
addper=[30,70,15,40,65]
addper.sort(reverse=True)
for i in addper:
if (oriper/oripri) > (oriper+i)/(oripri+addpri):
break
else:
oriper+=i
oripri+=addpri
print (int(oriper/oripri))
#include <iostream>
#include <set>
#include <functional>
using namespace std;
int main(int argc, const char * argv[]) {
int cost, perf, addon_cost, n;
cin >> cost >> perf >> addon_cost >> n;
set<int, greater<int>> parts_perf;
double eff = (double)perf / cost;
for (int i = 0; i < n; i++) {
int p;
cin >> p;
parts_perf.insert(p);
}
double max_eff = eff;
for (int p : parts_perf) {
cost += 3;
perf += p;
eff = (double)perf / cost;
if (max_eff < eff) {
max_eff = eff;
} else break;
}
cout << (int)max_eff << endl;
}
import java.util.Arrays;
import java.util.Comparator;
public class test {
public static void main(String[] argv) {
int beforeAct = 150;
int beforeMoney = 10;
Integer addAct[] = {30, 70, 15, 40 ,65};
int addMoney = 3;
int resultAct = 0;
int resultMoney = 0;
double result = 0.0;
double tempResult = 0.0;
Arrays.sort(addAct, new CompartorSort());
for(int i = 0 ; i < addAct.length; i ++){
resultAct = 0;
resultMoney = 0;
for(int j = 0; j <= i; j ++){
resultAct += addAct[j];
resultMoney += addMoney;
}
tempResult = (double)(resultAct + beforeAct) / (double)(resultMoney + beforeMoney);
if(result < tempResult){
result = tempResult;
}
}
System.out.println("최대 가성비 : " + result);
System.out.println("최대 가성비(Int형) : " + (int)result);
}
}
class CompartorSort implements Comparator<Integer>{
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if(o1 > o2){
return -1;
}else if(o1 == o2){
return 0;
}else {
return 1;
}
}
}
데이터분석 라이브러리인 Numpy를 사용하여 데이터를 분석하고 각 가성비의 차이를 비교 분석하였습니다.
import numpy as np
org_ppp= 150/10 # 원래 기계의 가성비 퍼포먼스/프라이스
prod = np.array([30, 70, 15, 40, 65]) # 각 기계의 성능
prod_ppp = prod // 3 # 각 기계의 가성비
print(prod_ppp)
print(prod[prod_ppp > org_ppp]) # 어떤 성능을 사용해야 기존 것보다 효율적인가
print(prod_ppp > org_ppp) # 가성비의 효율성이 높으면 True 낮으면 False
print(prod_ppp - org_ppp) # 가성비가 얼마나 차이가 나느냐
# Output:
#[10 23 5 13 21]
#[70 65]
#[False True False False True]
#[ -5. 8. -10. -2. 6.]
Python
import itertools
mac_pri = 10
mac_eff = 150
add_pri = 3
add_eff = [30, 70, 15, 40, 65]
max_eff = 0
ans = 0
for i in range(1, len(add_eff)+1):
for v in itertools.combinations(add_eff, i):
pri = mac_pri
eff = mac_eff
for a in v:
pri += add_pri
eff += a
if eff//pri > max_eff:
max_eff = eff//pri
ans = v
print(ans)
Python 3.6.4
init_p = 10
init_performance = 150
add_p = 3
add_performance = [30, 70, 15, 40, 65]
add_performance.sort(reverse=True)
for i in add_performance:
if (init_performance + i) / (init_p + add_p) > (init_performance / init_p):
init_p += add_p
init_performance += i
else:
break
print(init_performance / init_p)
17.8125
public class Pratice2 {
public static void main(String[] args) {
int Mprice = 10;
int Mp = 150;
int r = Mp / Mprice;
int[] add = { 30, 70, 15, 40, 65 };
for (int i = 0; i < add.length; i++) {
Mprice += 3;
Mp += add[i];
if (r > Mp / Mprice) {
Mprice -= 3;
Mp -= add[i];
}
}
System.out.println(Mp / Mprice);
}
}
original_cost_effectiveness = 150 / 10
add_part_performance = [30, 70, 15, 40, 65]
count_add_part = 0
max_cost_effectiveness = 0
for i in add_part_performance:
if i/3 > original_cost_effectiveness:
count_add_part += 1
max_cost_effectiveness += i
print((max_cost_effectiveness + 150) // (10 + count_add_part * 3) )
def greedy(price, performance, add_price, add_performance):
result = 0 # 최대 가성비
for index, pick in enumerate(add_performance):
sum = 0
for i in range(0, index+1):
sum += add_performance[i] # 추가 부품들의 합
efficiency = (performance + sum) / (price + add_price*(index+1))
if result < efficiency:
result = efficiency # 결과 값 갱신
return int(result)
price = int(input("원래 기계의 가격은? : "))
performance = int(input("원래 기계의 성능은? : "))
add_price = int(input("추가 부품의 가격은? : "))
add_perform = input("추가 부품의 성능은? : ")
add_perform = add_perform.split(',')
add_performance = list(map(int, add_perform))
add_performance.sort(reverse=True) # 내림차순으로 정렬 해놓고
result = greedy(price, performance, add_price, add_performance)
print(result)
Python 3.6
ori_pr = 10
ori_pf = 150
cur_pr = ori_pr
cur_pf = ori_pf
part = [('p1',3,30),('p2',3,70),('p3',3,15),('p4',3,40),('p5',3,65)]
part = sorted(part, key = lambda x : x[2]/x[1],reverse=True)
i =0
for p in part:
v = cur_pf/cur_pr # 현재 가성비
if v > p[2]/p[1]: break # 부품의 가성비와 현재 가성비 비교
cur_pr += p[1] # 가격, 성능 갱신
cur_pf += p[2]
i += 1 # 부품 인덱스 정보
print('''최대 가성비: {}
추가된 부품 목록: {}'''.format(int(v),part[:i]),end='')
파이썬입니다.
performL = [30, 70, 15, 40, 65]
performL.sort(reverse = True)
per = 150
pri = 10
for p in performL:
r = per / pri
if (per + p) / (pri + 3) > r:
per += p
pri += 3
else: break
print(per//pri)
def machine(price, spec, a_price, a_spec):
save=[]
numerator=0
ratio=spec/price
ratio_list= [one/a_price for one in a_spec]
for cal_one in ratio_list:
if ratio<cal_one:
save+=[a_spec[(ratio_list.index(cal_one))]]
for saveone in save:
numerator+=saveone
numerator+=spec
denumerator=price+a_price*int(len(save))
optimal=numerator/denumerator
return optimal, save
cost = 10
perform = 150
a_cost = 3
a_perform = [30,70,15,40,65]
print((perform+max(a_perform))//(cost+a_cost))
o_p = 10
o_v = 150
a_p = 3
a_v = [30, 70, 15, 40, 65]
res=15
a_v.sort(reverse=True)
for x in a_v:
o_v += x
o_p +=3
if o_v/o_p>res:
res=o_v/o_p
else:
break
print('%d'%(res))
// =======================================
double money = 10;
double exp = 150;
double price = 3;
double temp = 0;
double[] addex = { 30, 70, 15, 40, 65 };
Arrays.sort(addex);
for (int i = addex.length - 1; i > -1; i--) {
exp += addex[i];
money += price;
temp = temp < exp / money ? exp / money : temp;
}
System.out.println((int) temp);
omp = 10 # 원래 기계의 가격
om_p = 150# 원래 기계의 성능
adp = 3# 추가 부품의 가격
ad_p = [30, 70, 15, 40, 65]# 추가 부품의 성능
ad_p.sort(reverse=True)
# reverse=True는 내림자순 정렬을 하는 것이다.
for i in ad_p:
if om_p / omp > (omp + i) / (om_p + adp):
break
else:
omp += i
om_p += ad_p
print(om_p/omp)
machine_price = 10
machine_performance = 150
add_price = 3
add_performance = sorted([30, 70, 15, 40, 65], reverse=True)
print(add_performance)
price = machine_price
performance = machine_performance
value = []
price_list=[]
performance_list=[]
for i in add_performance:
price += add_price
price_list.append(price)
performance += i
performance_list.append(performance)
value.append(performance/price)
print(price_list)
print(performance_list)
print(value)
print(max(value)//1)
class Cost_performance:
parts_performance = [30,70,15,40,65]
newparts_cost = int(3)
def __init__(self,cost,performance):
self.cost = int(cost)
self.performance = int(performance)
a = Cost_performance(10,150)
for i in a.parts_performance:
if a.performance/a.cost > (a.performance+i)/(a.cost+a.newparts_cost):
break
else:
a.performance +=i
a.cost += a.newparts_cost
print(a.performance // a.cost)
클래스를 사용하여 한번 만들어 봤습니다. 틀린 부분이 있으면 수정 부탁드립니다. 초보라서요 ㅠㅠ
mp = int(input("machine price : "))
mv = int(input("machine value : "))
cp = int(input("component price : "))
cvs = input("components' value : ").split()
cvs.sort()
cvs.reverse()
avg = float(mv / mp)
for i in range(len(cvs)):
sum_cvs = sum([int(cvs[index]) for index in range(i+1)])
new_avg = float((mv + sum_cvs) / (mp + cp*(i+1)))
if new_avg > avg:
avg = new_avg
print(int(avg))
#include <stdio.h>
int main() {
int or_price = 10;
int or_per = 150;
int add_price = 3;
int add_per[5] = { 30,70,15,40,65 };
int max = 0;
int add_max=0;
int pri_count = 0;
int result[5]={0,};
int number=0;
int i,j;
for(j=0;j<5;j++){
for(i=0;i<5;i++){
if(add_per[i]>max){
max=add_per[i];
number=i;
}
}
add_per[number]=0;
pri_count+=1;
add_max+=max;
result[j]=(or_per+add_max)/(or_price+(add_price*pri_count));
max=0;
}
for(i=0;i<5;i++){
if(result[i]>max)
max=result[i];
}
printf("가성비 : %d\n",max);
//printf("%d\n", max);
//printf("%d",add_per[1]);
return 0;
}
# python 3.7.1
current_price = 10
current_perf = 150
add_price = 3
add_item = [30, 70, 15, 40, 65]
perf = 150/10
while True:
if max(add_item)/add_price > current_perf/current_price:
current_price += add_price
current_perf += max(add_item)
add_item.remove(max(add_item))
else:
break
print(current_perf/current_price)
import java.util.Arrays;
public class KimSanghyeop
{
public static void main(String[] args)
{
int[] arr = {30,70,15,40,65};
Arrays.sort(arr);
int money=10;
int power=150;
int avg=0;
int max=0;
int f1;
for(f1=1;f1<6;f1++)
{
power+=arr[5-f1];
money +=3;
avg = power / money;
if(avg > max)
{
max=avg;
}
}
System.out.println("최대효율 : "+max);
}
}
op = int(input("original price : ")) # op = original price
opf = int(input("original performance : ")) # opf = original performance
ap = int(input("add-on price : ")) # ap = add-on price
apf = list(map(int,list(input("add-on performance list : ").split(' ')))) # apf = add-on performance
tmp = opf / op
while apf :
opf += max(apf)
apf.remove(max(apf))
op += ap
if tmp < opf / op :
tmp = opf / op
else : break
print(int(tmp))
class reasonable():
price = 10
quality = 150
cost = 3
add_on = {1:30, 2:70, 3:15, 4:40, 5:65}
record = []
def add(self, number):
for i in range(2):
if i == 1:
self.price += self.cost
self.quality += self.add_on[number]
if number == 5:
self.record.append(float(self.quality/self.price))
self.price = 10
self.quality = 150
break
self.add(number+1)
return self.record
choice = reasonable()
result = max(choice.add(1))
print(round(result, 2))
def machine(p,per,ap,*apers):
np,nap = per,p
for aper in apers:
if per/p < aper/ap:
np += aper
nap += ap
print(int(np/nap))
org_cost=10
org_translate=150
new_cost=3
list_translate=[30,70,15,40,65]
list_result=[]
for i in list_translate:
result_translate = (org_translate + i) // 13
list_result.append(result_translate)
print(list_result)
price = 10
perf = 150
com_price = 3
com_perf = [30, 70, 15, 40, 65]
com_perf.sort()
for p in com_perf:
if (perf + p) / (price + com_price) > perf/price:
perf += p
price += com_price
result = perf // price
else:
continue
print(result)
addtion_performance = [30, 70, 15, 40, 65]
original_value = 10
original_performance = 150
additional_value = 3
def cal_per(sum,index,count) :
a=0
b=0
if index == len(addtion_performance):
return sum/(10+3*count)
a=cal_per(sum,index+1,count)
sum+=addtion_performance[index]
b=cal_per(sum,index+1,count+1)
if a>b :
return a
else :
return b
print(int(cal_per(150,0,0)))
a = 150 #원래 기계의 성능
b = 10 #원래 기계의 가격
c = [30, 70, 15, 40, 65] #추가 부품의 성능
c.sort(reverse = True) #추가 부품을 성능순으로 정렬
e = []
for i in c: #가장 성능이 좋은 부품부터 더한다.
a += i
b += 3
d = a // b #d = 효율
e.append(d) #e라는 리스트에 효율을 기록해놓는다.
e.sort(reverse = True) #효율을 크기순으로 정렬
print(e[0]) #가장 큰 효율값을 print
namespace codingdojang_test
{
class Program
{
static void Main(string[] args)
{
int org_price = int.Parse(Console.ReadLine());
int org_performance = int.Parse(Console.ReadLine());
int add_price = int.Parse(Console.ReadLine());
string add_performance = Console.ReadLine();
int add_performance_max = 0;
string[] add_performance_array = add_performance.Split(',');
int temp = 0;
Array.Sort(add_performance_array);
Array.Reverse(add_performance_array);
for (int i = 1; i <= add_performance_array.Length; i++)
{
for (int e = 0; e < i; e++)
{
temp += int.Parse(add_performance_array[e]);
}
if (add_performance_max < temp / (i * add_price))
{
add_performance_max = temp;
}
temp = 0;
}
Console.WriteLine((org_performance + add_performance_max) / (org_price + add_price));
}
}
}
ori_price=10
ori_perform=150
plus_price=3
plus_perform_list = [30,70,15,40,65]
plus_perform_list.sort(reverse=True) # 성능 높은 것 부터 정렬
p_to_p = ori_perform/ori_price
for plus in plus_perform_list:
if p_to_p<(ori_perform+plus)//(ori_price+3):
ori_price+=3
ori_perform+=plus
p_to_p = ori_perform//ori_price
print(p_to_p)
oriperf=150
oriprice=10
addperf=[30,70,15,40,65]
addperf.sort()
addperf.reverse()
addprice=3
max=oriperf/oriprice
totalperf=oriperf
totalprice=oriprice
number=0
for i in range(len(addperf)):
totalperf+=addperf[i]
totalprice+=addprice
rat=totalperf/totalprice
if rat>max:
max=rat
number=i
print(int(max))
print(addperf[:number+1])
원래기계가성비 = 150/10
추가부품가격 = 3
추가부품성능 = [30, 70,15,40,65]
for i in 추가부품성능:
if i/3 > 원래기계가성비:
print("추가 가능한 부품의 성능" , int(i))
print("추가 부품의 최대 가성비" , int(i/3))
"""
#output
추가 가능한 부품의 성능 70
추가 부품의 최대 가성비 23
추가 가능한 부품의 성능 65
추가 부품의 최대 가성비 21
"""
가격 = 10;성능 = 150;부품_가격 = 3;부품_성능 = [30,70,15,40,65]
print(x for x in 부품_성능) print(list(x for x in 부품_성능)) print((성능 + max(list(x for x in 부품_성능)))//(가격+부품_가격))
print((성능+max(list(x for x in 부품_성능)))//(가격+부품_가격))
from itertools import combinations
orgp = 10
orgpe = 150
addp = 3
addpe = [30, 70, 15, 40, 65]
combi1 = tuple(addpe)
combi2 = list(combinations(addpe, 2))
combi3 = list(combinations(addpe, 3))
combi4 = list(combinations(addpe, 4))
combi5 = []
for k in addpe:
tupl = k,
combi5.append(tupl)
sumCombi = combi5 + combi2 + combi3 + combi4
sumCombi.append(combi1)
print(sumCombi)
Max_P = 0
for i in sumCombi:
sum = 0
for j in i:
sum += j
effectP = (orgpe + sum) / (orgp + (3*len(i)))
if Max_P <= effectP:
Max_P = effectP
Dev = i
print('최대 가성비는 추가 부품 ', *Dev, '로 구성되며 가성비는 ', int(Max_P), '이다')
x=10
xx=150
y=3
yy = sorted([30, 70, 15, 40, 65])
yy.reverse()
a=0
for i in yy:
xx+=i
x+=y
r= xx/x
if r>=a:
a=r
else:
break
print(int(a))
ori_price = 10
ori_perform = 150
add_price = 3
add_perform = [30, 70, 15, 40, 65]
add_perform.sort(reverse = True)
for i in add_perform:
cost = ori_perform / ori_price
new_cost = (ori_perform + i) / (ori_price + add_price)
if cost > new_cost:
break
else:
ori_perform += i
ori_price += add_price
print(ori_perform // ori_price)
import itertools
def maxbenefit(cost,perform,addCost,addPerform):
combs =[]; result = []
for i in range(1, len(addPerform)+1):
els = [list(x) for x in itertools.combinations(addPerform,i)]
combs.extend(els)
for i in range(len(combs)):
result.append((perform + sum(combs[i])) // (cost + addCost*len(combs[i])))
return max(result)
print(maxbenefit(10,150,3,[30,70,15,40,65]))
'''
apeend와 expend의 차이
x = [1,2,3]
x.append([4,5])
[1,2,3,[4,5]] 객체를 맨뒤에 추가
x.extend([4,5])
[1,2,3,4,5] 객체의 원소로 추가
'''
#가성비 최대화
or_pc = 10
or_pf = 150
ad_pc = 3
ad_pf = [30, 70, 15, 40, 65]
number = 0
j = 0
temp = 0
l = len(ad_pf)
while j < len(ad_pf):
i = j
while i < len(ad_pf)-1:
if ad_pf[j] < ad_pf[i+1]:
temp = ad_pf[j]
ad_pf[j] = ad_pf[i+1]
ad_pf[i+1] = temp
i = i +1
j = j+1
print(ad_pf)
pf=or_pf
pc=or_pc
ce_list = []
j=0
while j < len(ad_pf):
pf= pf+ad_pf[j]
pc= pc + ad_pc
ce=pf/pc
ce_list.append(ce)
if j>0 and ce_list[j-1] > ce_list[j]:
del ce_list[j]
break
j=j+1
print(ce_list)
print("답:",int(ce_list[j-1]))
# get number that program suggest
m_price = int(input("Write original price"))
m_performance = int(input("Write original performance"))
e_price = int(input("Write extra price"))
a = int(input("Write extra machine's counts"))
e_machine = []
list_1 = []
p = []
# sort by reverse
for i in range(a):
b = int(input())
e_machine.append(b)
e_machine.sort(reverse = True)
# algorithm
list_1.append(m_performance / m_price) # get first Value for money
p.append(m_performance) # ger first add of machine performance
for i in range(a):
k = p[i] + e_machine[i] # k = add of machine performance
p.append(k)
for i in range(a):
t = 10 + e_price * (i + 1) # t = total prince
k = p[i+1] / t # k = total performance / t
list_1.append(k)
list_1.sort(reverse = True) # sort by reverse
# output
if list_1[0] % 1 > 0:
print("%.0f" %int(list_1[0]//1)) # if output has decimal point, discard decimal point
else:
print(list_1[0])
JAVA
public class MaxEffefiencyPerCost {
public static void main(String[] args) {
int originPrice = 10;
int originPerfor = 150;
int[] extraPerfor = new int[] {30, 70, 15, 40, 65};
int plusPrice = 0;
int plusPerfor = 0;
double[] eff = new double[extraPerfor.length];
double maxEff = 0;
//1. 성능이 높은 추가 부품이 앞에 오게 sorting 한다. ~ bubble sort 사용
for(int i=0; i<extraPerfor.length-1; i++) {
for(int j=0; j<extraPerfor.length-1-i; j++) {
if(extraPerfor[j]<extraPerfor[j+1]) {
int temp = extraPerfor[j];
extraPerfor[j] = extraPerfor[j+1];
extraPerfor[j+1] = temp;
}
}
}
// 2. [0]부터 [n]까지 더했을 때의 가성비를 구한다.
for(int i=0; i<extraPerfor.length-1; i++) {
plusPerfor += extraPerfor[i];
plusPrice += 3;
eff[i] = ( ((originPerfor+plusPerfor)*10) / ((originPrice+plusPrice)*10) );
System.out.println(eff[i]);
if(eff[i+1]<eff[i]) {
maxEff = eff[i];
break;
}
}
System.out.print(Math.round(maxEff));
}
}
PHP
$o_price = 10;
$o_performance = 150;
$p_price = 3;
$p_performances = [30, 70, 15, 40, 65];
$result = 0;
rsort($p_performances);
foreach ($p_performances as $p_performance) {
$o_cost_effective = $o_performance / $o_price;
$a_cost_effective = ($o_performance + $p_performance) / ($o_price + $p_price);
if ($o_cost_effective <= $a_cost_effective) {
$o_performance += $p_performance;
$o_price += $p_price;
continue;
}
$result = intval($o_performance / $o_price);
break;
}
print_r($result); // 17
add_perform = [30, 70, 15, 40, 65] add_perform.sort() add_perform.reverse() print(add_perform)
result = [] performance = 150 price = 10
for i in range(len(add_perform)):
eff = performance / price
result.append(eff)
performance += add_perform[i]
price += 3
print(result)
def Max_Value(a, b, c, d): # a는 원래 기계 가격, b는 원래 기계 성능, c는 부품 가격, d는 추가 부품 성능 리스트
result = b / a
d.sort(reverse=True) # 성능이 높은 부품순으로 정렬
for i in d:
a += c
b += i
if b / a > result:
result = b / a
else:
break # 더이상 가성비가 좋아지지 않으면 그만 계산한다. 성능이 높은 순으로 정렬되어 있음으로.
return(result)
d = [30, 70, 15, 40, 65]
print("Max Value is : %d" % Max_Value(10, 150, 3, d))
price = [30, 70, 15, 40, 65]
origin = 150 /10
add_price = 3
max_value = origin
count = 0
for i in price:
if i/add_price > origin:
print("{}은 가성비 좋음, 가성비 : {}".format(i,i//add_price))
if i/add_price > max_value:
max_value = i//add_price
count = i
else :
print("{}은 가성비 않 좋음, 가성비 : {}".format(i,i//add_price))
print("{} 최대 가성비 {}입니다. ".format(count,max_value))
python 3.7.4
ori_co = 10
ori_per = 150
add_co = 3
add_per = [30, 70, 15, 40, 65]
per_co = [(ori_per+i) // (ori_co+add_co) for i in add_per]
per_co.sort()
print(per_co[-1])
package practiceLv1;
import java.util.*;
public class 가성비최대화 {
public static void main(String[] argv) {
int beforeAct = 150;
int beforeMoney = 10;
Integer addAct[] = {30, 70, 15, 40 ,65};
int addMoney = 3;
int resultAct = 0;
int resultMoney = 0;
double result = 0.0;
double tempResult = 0.0;
Arrays.sort(addAct, Collections.reverseOrder());
//배열을 내림차순으로 정렬하는 방법
for(int i = 0 ; i < addAct.length; i ++){
resultAct = 0;
resultMoney = 0;
for(int j = 0; j <= i; j ++){
resultAct += addAct[j];
resultMoney += addMoney;
}
tempResult = (double)(resultAct + beforeAct) / (double)(resultMoney + beforeMoney);
if(result < tempResult){
result = tempResult;
}
}
System.out.println("최대 가성비 : " + result);
System.out.println("최대 가성비(Int형) : " + (int)result);
}
}
int Efficient(int Add_Eff[])
{
int cost = 10;
int Eff = 150;
int result = Eff / cost;
int cost_addition = 3;
int result_Compare = result;
for(int i =0; i<5; i++)
{
cost += cost_addition;
result_Compare = Eff + Add_Eff[i] / cost+cost_addition;
result > result_Compare ? break:result = result_Compare ;
}
return result;
}
originalmachineprice = 10
originalmachineperformance = 150
additionalmachineprice = 3 # 최초 변수 설정
additionalmachineperformance = [30,70,15,40,65]
result = []
additionalmachineperformance.sort(reverse=True) # 이거로 끝나고 이걸 변수할당해서 새로운거를 구하는건 아니다
print(additionalmachineperformance)
# 한개씩 넣어서 결과값을 내서 뭔가랑 비교를 해서 판단한 후 스탑할지 멈출지. 또는 하나씩 해서 맥스값을 구하는...
# 바로 전 가성비랑 비교해서 작아지면 스탑?
# 최대가성비를 구하는 것이므로 다 구해서 그냥 맥스값 때리면 될 듯(다만 리스트를 소트해서)
for i,k in enumerate(additionalmachineperformance):
originalmachineperformance += k
print(originalmachineperformance)
result.append(originalmachineperformance/(10+3*(i+1)))
print(result)
print(max(result))
import math
St = [30,70,15,40,65]
St_sort = sorted(St,reverse=True)
print(St_sort)
Fc = int(150)
Gasungbi = []
for a in range (0,5):
Fc += int(St_sort[a])
print(Fc)
z=((Fc/(10 + (3*(a+1)))))
Gasungbi.append(z)
print(z)
print("MAX GASUNGBI =",int(max((Gasungbi))))
package Price;
public class Rational_Price {
public static void main(String[] args) {
// TODO Auto-generated method stub
int ex_price = 10;
int ex_performance[] = {150,150,150,150,150};
int extra_price = 3;
int extra_performance[] = {30,70,15,40,65};
int total_price[] = {0,0,0,0,0};
int end_price=0;
int rational_price = 45;
for(int i =0; i<extra_performance.length; i++) {
if(extra_performance[i]>45)
total_price[i]+= ex_performance[i] + extra_performance[i];
else
total_price[i] +=ex_performance[i];
}
for(int s : total_price)
System.out.println("가성비 부품의 가격 : " + s);
for(int j=0;j<5;j++) {
end_price +=total_price[j];
}
System.out.println("\n가성비 장비의 가격 : " + end_price);
System.out.println("\n최대 가성비 : " + end_price/5);
}
}
p = 10
f = 150
exp = 3
exf = [30, 70, 15, 40, 65]
conseq = []
exf1 = sorted(exf, reverse=True)
for i in exf1:
L = (f+i)//(p+exp)
conseq.append(L)
f += i
p += exp
print(max(conseq))
파이썬입니다
추가 부품과 성능이 어떻게 입력되는지에 따라 경우의 수를 나누어 풀었습니다
from decimal import Decimal as D
from itertools import combinations as C
# 입력
o_price = int(input('원래 기계의 가격: '))
o_perform = int(input('\n원래 기계의 성능: '))
while True:
ex_price = list(map(int, input('\n추가 부품의 가격: ').split(',')))
ex_perform = list(map(int, input('\n추가 부품의 성능: ').split(',')))
if len(ex_price) == 1 or len(ex_perform) == 1 or len(ex_price) == len(ex_perform):
break
print('\n추가 부품의 가격과 성능은 하나로 통일되거나 각각 매칭되어야 합니다.')
if len(ex_price) != len(ex_perform):
if len(ex_price) == 1:
ex_price *= len(ex_perform)
else:
ex_perform *= len(ex_price)
# 최대 가성비 찾기
ratio = D(o_perform)/D(o_price)
for i in range(len(ex_perform)):
cases = list(C(range(len(ex_perform)), i))
for j in cases:
n = D(o_perform) + D(sum(list(map(lambda x: ex_perform[x], j))))
d = D(o_price) + D(sum(list(map(lambda x: ex_price[x], j))))
if n / d > ratio:
ratio = n / d
print('\n추가 부품을 장착하여 얻을 수 있는 최대 가성비: {}'.format(int(ratio)))
machine_cost = 10 machine_func = 150 part_cost = 3 part_func = [30, 70, 15, 40, 65]
print((machine_func+max(list(x for x in part_func)))//(machine_cost+part_cost))
윗분 코딩 짠 것 참고
파이썬 3.7
machine = 150
machine_price = 10
add = [30, 70, 15, 40, 65]
adg_price = 3
add_gear = 0
result = 0
i = 1
while True:
add_gear += max(add)
add.remove(max(add))
pfm = (machine + add_gear) / (machine_price + adg_price * i)
if result < pfm:
result = pfm
else:
break
i += 1
print(int(result))
ogcost = 10
ogperf =150
addcost = 3
addperf = [30, 70, 15, 40, 65]
maxpt = 17
gyunjuk = []
for i in addperf:
gj = (ogperf + i) / (ogcost + addcost)
if gj > maxpt:
gj = maxpt
gyunjuk.append(round(gj, 2))
print('각 부품을 착용 했을때의 견적 입니다.\n' + str(gyunjuk))
print('\n\n가장 높은 가성비는', max(gyunjuk), '입니다.')
def a(v,p):
return v/p
l=[30,70,15,40,65]
v=150
p=10
l.sort(reverse=True)
for i in l:
if i/3>=a(v,p):
v+=i
p+=3
else:
break
print(int(a(v,p)))
"""
부족하나마 풀이 올려봅니다.
a를 기존 조합의 가성비, k를 기존 부품 가격 합, b를 추가할 부품 가성비라 하면,
부품 하나를 추가할 때의 가성비는 (ak+3b)/(k+3)이고, 기존 가성비 a를 뺀 식은 3(b-a)입니다.
따라서 기존 부품 가격 합에 무관하게 a=<b 이면 가성비가 증가하거나 유지되고,a>b이면 가성비는 감소합니다.-ㄱ
반대로 전체 가성비보다 가성비가 낮은 부품을 빼면 전체 가성비는 증가합니다.-ㄴ
한편, 최고 가성비를 가지는 조합의 부품들의 가성비 조합을 A={a1,a2...an}(내림차순)라 하고,
A의 원소 각각에 대응하는 부품을 가진 조합의 전체 가성비를 s로 놓아 보겠습니다.
1) 만약 x>a1이면서 A에 포함되어 있지 않은 부품 x가 존재한다고 가정하면,
ㄱ에 따라 s보다 A에 x를 추가한 조합의 가성비가 높습니다.
그러면 A가 최고 가성비 조합이라는 전제에 모순이므로, x는 존재하지 않습니다.
즉, a1이 추가 가능한 전체 부품 중 가장 가성비가 높은 부품입니다.
2) 만약 an이 s보다 가성비가 낮으면, ㄴ에 따라 A에서 an을 뺀 집합의 가성비가 s보다 높습니다.
따라서 이 경우 역시 마찬가지로 A가 최고 가성비 조합이라는 전제에 모순이므로, an은 s보다 가성비가 높거나 같습니다.
3) A의 원소를 ak(k=1,2...n)이라 하면, ak>=an 이므로, ak>=s 입니다.
1),2),3)과 부품 가격이 같다는 조건에 따라 A는 추가 가능한 전체 부품 집합을
성능에 따라 내림차순으로 정렬한 집합의 가장 왼쪽 원소부터 n번째 까지의 원소를 포함하는 집합입니다.
따라서, 최고가성비 부품부터 차례로 A에 포함시키면서 전체 집합의 가성비와 추가할 부품의 가성비를
비교/판단하여 A에 포함시키고, 집합의 전체 가성비보다 낮은 가성비를 갖는 부품부터
A에 추가하는 작업을 중단하면 A가 최고 가성비 집합이 됩니다.
"""
def bin(x):
xbin=[]
while (x>0):
xbin.insert(0,x%2)
x=x//2
while (len(xbin)<5):
xbin.insert(0,0)
return(xbin)
performm,max,maxx=[30,70,15,40,65],0,[]
for i in range (0,32):
price, perform,calc=10,150,[]
for j in range (0,5):
perform+=performm[j]*bin(i)[j]
price+=3*bin(i)[j]
calc.append(performm[j]*bin(i)[j])
while (0 in calc):
calc.remove(0)
if max<perform/price:
max, maxx=perform/price, calc
print (maxx, int(max))
x = 150
x_price = 10
add = [30, 70, 15, 40, 65]
add_price = 3
add.sort(reverse = True)
for i in add :
stat = (x / x_price)
new_stat = (x + i) / (x_price + add_price)
if stat > new_stat :
break
else :
x += i
x_price += add_price
print(x // x_price)
price_ = int(input('기계의 가격'))
power_ = int(input('기계의 성능'))
price_add = int(input('추가 부품의 가격'))
power_add = input('추가 부품의 각 성능').split()
all_price_ = 0
add_ons = list()
sum_power_ = 0
price_per_power_ = 0
for i in power_add:
change_i = int(i)
if change_i/price_add > power_/price_:
add_ons.append(change_i)
all_price_ += price_add
for j in add_ons:
sum_power_ += j
price_per_power_ = int((sum_power_+power_)/(all_price_+price_))
print('최대 가성비는 %d' %(price_per_power_))
파이썬.
파이썬
orp = 10 #원래 가격
ore = 150 # 원래 성능
adp = 3 #추가되는 가격 (가격은 모두 동일함)
ade = [30,70,15,40,65] #추가되는 기계들의 성능
ade.sort(reverse=True)
print(ade)
for i in ade:
if ore/orp < (ore+i)/(orp+3):
ore += i
orp += 3
else:
print(int(ore/orp))
break
pr=10
pf=150
adpr=3
adpf=[30,70,15,40,65]
for i in adpf:
if (pf/pr)>(pf+i)/(pr+adpr):pass
else:
pf+=i
pr+=adpr
print(pf/pr)
from itertools import combinations
machine_price = 10 #원래 기계의 가격
per_m = 150 # 원래 기계의 성능
add_m = 3 # 추가 부품의 가격
add_m_p = [30, 70, 15, 40, 65] # 추가 부품의 성능
com_2 = list(combinations(add_m_p,2)) # 두개의 추가 부품의 모든 조합 리스트
com_3 = list(combinations(add_m_p,3)) # 세개의 추가 부품의 모든 조합 리스트
com_4 = list(combinations(add_m_p,4)) # 네개의 추가 부품의 모든 조합 리스트
com_5 = list(combinations(add_m_p,5)) # 다섯개의 추가 부품의 모든 조합 리스트 (30,70,15,40,65) 임
list_com_1 = []
list_com_2 = []
list_com_3 = []
list_com_4 = []
list_com_5 = []
# 원래의 기게 가격에 각각 한개의 부품을 더했을 때 가능한 가성비 리스트
for j in add_m_p:
efficiency_one_added = (per_m + j)/(machine_price+add_m)
list_com_1.append(efficiency_one_added)
# 원래의 기게 가격에 모든 두개의 조합의 부품을 더했을 때 가능한 가성비 리스트
for i in com_2:
efficiency_2 = (per_m + i[0]+i[1])/(machine_price+add_m*2)
list_com_2.append(efficiency_2)
# 원래의 기게 가격에 모든 세개의 조합의 부품을 더했을 때 가능한 가성비 리스트
for i in com_3:
efficiency_3 = (per_m + i[0]+i[1]+i[2])/(machine_price+add_m*3)
list_com_3.append(efficiency_3)
# 원래의 기게 가격에 모든 네개의 조합의 부품을 더했을 때 가능한 가성비 리스트
for i in com_4:
efficiency_4 = (per_m + i[0]+i[1]+i[2]+i[3])/(machine_price+add_m*4)
list_com_4.append(efficiency_4)
# 원래의 기게 가격에 모든 다섯개의 부품을 더했을 때 가능한 가성비 리스트
for i in com_5:
efficiency_5 = (per_m + i[0]+i[1]+i[2]+i[3]+i[4])/(machine_price+add_m*5)
list_com_5.append(efficiency_5)
# 각각의 경우에서 구한 가성비 리스트를 다 합친 리스트
total_list = list_com_1+list_com_2+list_com_3+list_com_4+list_com_5
# 전체 리스트에서 최대 가성비 값을 찾음
max_eff = max(total_list)
print("최대 가성비: %0.2f..-> %i" % (max_eff, max_eff))
import math
origin_price = 10
origin_abil = 150
add_price = 3
add_list=[30,70,15,40,65]
add_list.sort(reverse=True)
print(add_list)
result_max=(origin_abil+add_list[0])/(origin_price+add_price)
for i in range(0,len(add_list)+1) :
result_temp=(origin_abil+sum(add_list[:i]) ) / (origin_price + (add_price*i))
if result_temp>result_max :
result_max = result_temp
result_max = math.trunc(result_max)
print(result_max)
파이썬3입니다.
기본가격,성능 부품가격,성능
모두 임의로 설정했습니다.
import random as r
from itertools import combinations as cb
#Basic info.
b_price = r.randrange(100, 500, 100) #Basic price
b_per = r.randrange(100, 500, 100) #Basic performance
#Parts info.
p_price = r.randrange(50, 300, 50) #Parts price
p_per = [r.randrange(20, 200, 20)] #Parts performance
p_num = r.randint(2, 10) # The number of parts.
p_com = [r.randrange(100, 500, 50) for _ in range(p_num)] #Combination of parts
#Parts combination and calculating price
p_cper = [list(cb(p_com, i)) for i in range(p_num + 1)] #Combination of parts performance
p_cper = [y for x in p_cper for y in x] #Flatten combination of parts performance
p_total_cper = [sum(i) for i in p_cper] #Sum of combination of parts performance
p_total_parts = [len(i) for i in p_cper] #The number of parts used in combination of parts
#Total Performance and Toral price
t_per = [b_per + p_total_cper[i] for i in range(len(p_total_cper))] #Total perform = basic perform + parts perform
t_price = [b_price + p_price * p_total_parts[i] for i in range(len(p_total_parts))] #Total Price = basic price + parts price
#RESULT
ppp = [round(t_per[i] / t_price[i], 1) for i in range(len(t_per))] #Cost_effectiveness = total perform / total price
mp = max(ppp) # Max cost_effectiveness.
mpc = ppp.index(mp) # Max cost effetivenes combination.
#PRINT OUT
print(f'Basic price is {b_price} and Basic performance is {b_per}W')
print(f'Parts price is {p_price} and Parts performance is {p_com}W\nThe number of parts is {p_num}')
print(f'Max cost effectiveness is {mp} and \nthe combination of max is {p_cper[mpc]}')
public class machine {
private int price;
private int power;
public machine(int price, int power) {
this.price = price;
this.power = power;
}
public double nowE(){
return (double)power/price;
}
}
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("가격 얼마인가요? ");
int price = scan.nextInt();
System.out.print("성능? ");
int power= scan.nextInt();;
machine a = new machine(price,power);
int[] addOn = {30, 70, 15, 40, 65};
int totalPrice = price;
int totalPower = power;
for(int i=0;i<addOn.length;i++) {
if( (double)addOn[i]/3 > a.nowE())
{
totalPrice += 3;
totalPower += addOn[i];
} // 부품의 가성비가 기존 부품보다 훌륭한거만 추가
}
System.out.println("최대 가성비: "+ totalPower/totalPrice);
System.out.println("가격: "+ totalPrice);
System.out.println("성능: "+ totalPower);
}
}
add=[70,65,40,30,15]
mach_price=10
mach_abil=150
gasungbi=[15]
for i in add:
mach_price += 3
mach_abil += i
ratio = mach_abil / mach_price
gasungbi.append(ratio)
int(max(gasungbi))
파이썬으로 작성하였습니다.
machine_cost = 10
machine_work = 150
efficiency = machine_work/machine_cost
new_machine_work = 150
new_machine_cost = 10
addon_work = [30, 70, 15, 40, 65]
addon_work.sort(reverse=True)
for x in addon_work:
new_machine_work += x
new_machine_cost += 3
new_machine_efficiency = new_machine_work/new_machine_cost
if new_machine_efficiency > efficiency:
efficiency = new_machine_efficiency
continue
else:
break
print(int(efficiency))
추가 부품의 가격은 모두 같기 때문에, 추가 부품의 성능이 가장 좋은 부품일수록 가성비가 높아집니다. 따라서 추가 부품의 리스트를 역순으로 정렬하고, 이를 하나씩 달아보면서 이전의 가성비 값과 비교하는 루프를 짜서 문제를 해결합니다.
public static void main(String[] args) {
int[] plusFunc = new int[] {30, 70, 15, 40, 65};
int oriFunc = 150;
int oriPrice = 10;
int plusPrice = 3;
for(int i = 0; i < plusFunc.length; i++) {
if(plusFunc[i] < (oriFunc/oriPrice)*3) {
continue;
}else {
oriFunc += plusFunc[i];
oriPrice += plusPrice;
}
}
System.out.println(oriFunc/oriPrice);
}
from itertools import combinations
class Optimizer:
def __init__(self,org_pri,org_per,add_pri,per):
self.org_pri = org_pri
self.org_per = org_per
self.add_pri = add_pri
self.per = per
self.opt = []
def calculateOptPer(self):
valmax = 0
for n in range(0,len(self.per)):
b = list(combinations(self.per,n+1))
for c in b:
sumpri = self.org_pri
sumper = self.org_per
for i in c:
sumpri += 3
sumper += i
val = sumper/sumpri
if val>valmax:
valmax = val
self.opt = [n+1,val,c]
print(self.opt)
org_pri = 10
org_per = 150
add_pri = 3
per = [30,70,15,40,65]
a = Optimizer(org_pri,org_per,add_pri,per)
a.calculateOptPer()
파이썬입니다, 처음에 가성비를 어떻게 구하는지 어이업게 고민했네요 주어진 조건만 생각하면 쉬운에 다른 조건들도 생각해보고 있었네요 ㅎ
import math
origin_price = 10
origin_perfom = 150
part_price = 3
parts_perfoms = [30, 70, 15, 40, 65]
total_prices = 0
total_perfoms = 0
total_prices += origin_price
total_perfoms += origin_perfom
for perfom in parts_perfoms:
if perfom/part_price > origin_perfom/origin_price:
total_prices += 3
total_perfoms += perfom
print(math.floor(total_perfoms/total_prices))
original_price = 10
original_performance = 150
parts_price = 3
parts_performance_list = [30, 70, 15, 40, 65]
parts_performance_list.sort(reverse=True)
for parts_performance in parts_performance_list:
if (original_performance / original_price) > \
(original_performance + parts_performance) / (original_price + parts_price):
break
original_performance += parts_performance
original_price += parts_price
print("성능이 %s인 부품을 추가하세요." % parts_performance)
print("최대 가성비는 %.2f 입니다." % (original_performance / original_price))
import math
price = 10
performance = 150
price_component = 3
performance_component = [30, 70, 15, 40, 65]
for i in performance_component:
if (performance+i)/(price+price_component) > performance/price:
performance += i
price += price_component
print("maximum price to performance:", math.floor(performance/price))
a=int(input("원래기계가격 "))
b=int(input("원래기계성능 "))
c=int(input("추가부품가격 "))
cc=int(input("추가부품개수 "))
d=[]
e=0
for i in range(1,cc+1):
e=int(input("%d번 부품 성능 " %i))
d.append(e)
g=0
k=[]
for i in d:
if i/c>b/a:
g+=i
k.append(i)
h=(g+b)/(c*len(k)+a)
print (int(h))
p_machine = 10
a_machine = 150
p_add = 3
a_add = [30, 70, 15, 40, 65]
p_tot = 0
a_tot = 0
list_temp = []
comb = []
num1 = []
for i in range(len(a_add)):
num1.append([a_add[i]])
print(num1)
num2 = []
count = 0
for i in a_add:
for j in a_add:
if len(set([i,j])) == 2:
if sorted([i,j]) not in num2:
num2.append(sorted([i,j]))
count += 1
print(num2, count)
num3 = []
count = 0
for i in a_add:
for k in a_add:
for j in a_add:
if len(set([i,k,j])) == 3:
if sorted([i,j,k]) not in num3:
num3.append(sorted([i,k,j]))
count += 1
print(num3, count)
num4= []
count = 0
for l in a_add:
for i in a_add:
for k in a_add:
for j in a_add:
if len(set([l,i,k,j])) == 4:
if sorted([l,i,k,j]) not in num4:
num4.append(sorted([l,i,k,j]))
count += 1
print(num4, count)
num5 = []
count = 0
for m in a_add:
for l in a_add:
for i in a_add:
for k in a_add:
for j in a_add:
if len(set([m,l,i,k,j])) == 5:
if sorted([m,l,i,k,j]) not in num5:
num5.append(sorted([m,l,i,k,j]))
count += 1
print(num5, count)
num = []
num.append(num1)
num.append(num2)
num.append(num3)
num.append(num4)
num.append(num5)
max = 0
max_arr = []
for i in range(5):
for each in num[i]:
add = each
a_add = sum(each)
p_add = len(each)*3
p_tot = p_machine + p_add
a_tot = a_machine + a_add
aperp = a_tot/p_tot
if aperp > max:
max = aperp
max_arr = [add, a_add, p_add, p_tot, a_tot, aperp]
print(max_arr)
def cost_effectiveness(m, me, p, pe):
result = []
temp = []
pe.sort()
for i in range(1,len(pe)+1):
denominator = me
molecular = m
temp.append(max(pe))
for i in temp:
denominator += i
molecular += p * len(temp)
result.append(denominator / molecular)
pe.pop()
print(round(max(result)))
cost_effectiveness(10, 150, 3, [30, 70, 15, 40, 65])
def Max_Find(price,power,plus_power,plus_price):
ori=power/price
for i in plus_power:
if ori<i/plus_price:
power=power+i
price=price+plus_price
ori=power/price
print("max : {0}".format(ori))
a=10
b=150
c=3
d=[30,70,15,40,65]
Max_Find(a,b,d,c)
주어진 가격/성능 뿐 아니라 사용자로부터 임의의 가격/성능을 입력 받았을 때 가성비 갑인 경우를 출력하게 짜보았습니다.
machine_price = int(input("기계의 가격을 입력하세요:"))
machine_performance = int(input("기계의 성능을 입력하세요:"))
parts_price = int(input("부품의 가격을 입력하세요:"))
n = int(input("부품의 개수를 입력하세요:"))
parts_performance = []
for i in range(0, n):
parts_performance.append(int(input("{}번째 부품의 성능을 입력하세요:".format(i +1))))
parts_performance.sort()
parts_performance.reverse()
answer = 0
for i in range(0, len(parts_performance)):
machine_price += parts_price
machine_performance += parts_performance[i]
if answer < machine_performance/machine_price:
answer = machine_performance/machine_price
elif answer > machine_performance/machine_price:
print("성능 좋은 순으로 부품 {}개를 추가 할 때 가성비가 가장 좋습니다.".format(i))
break
print("해당 제품의 가성비는 {}입니다.".format(int(answer)))
machine_price = 10
eff =150
component_price = 3
com_eff = [30,70,15,40,65]
max_eff = int(eff/machine_price + max([x/component_price for x in com_eff]))
max_eff
ori_cost = 10
ori_perfo = 150
add_perfo = [30, 70, 15, 40, 65]
add_perfo.sort(reverse=True)
tot_perfo = ori_perfo
tot_cost = ori_cost
for i in range(len(add_perfo)):
if tot_perfo/tot_cost >= (tot_perfo + add_perfo[i])/(tot_cost+3):
break
else:
tot_perfo += add_perfo[i]
tot_cost += 3
print(int(tot_perfo/tot_cost))
[파이썬]
a = [150, 10]
b = [30, 3]
c = [70, 3]
d = [15, 3]
e = [40, 3]
f = [65, 3]
ppp_a = a[0]/a[1]
grouping = [b, c, d, e, f]
sum_price = 150
sum_performance = 10
# 원래 부품 가성비보다 좋은 나머지 부품만 골라 더해준다
for i in grouping:
if ppp_a < (i[0]/i[1]):
sum_price += i[0]
sum_performance += i[1]
else:
pass
print(sum_price//sum_performance)
price = sorted([30,70,15,40,65],reverse=True)
upper = 150
lower = 10
result = 150/10
for i,j in enumerate(price):
upper = upper + j
lower = 10 + 3*(i+1)
if upper/lower-result < 0:
break
result = upper/lower
print(int(result))
orp = 10
org = 150
adp = 3
adg = [30, 70, 15, 40, 65]
adg.sort(reverse=True)
for i in adg:
if org / orp > (org + i) / (orp + adp):
break
else:
org += i
orp += adp
print(org / orp)
a = 10 #원래 기계의 가격
aa = 150 #원래 기계의 성:
extraP = 3
extra = [30,70,15,40,65]
extra.sort(reverse=True)
n = 0
k = {}
for i in extra:
n += 1
m = (aa+i)//(3*n+a)
k[i] = m
aa += i
print(max(k.values()))
여기서 key 값은 내림차순한 추가 기능의 성능값들이 누적되는 값입니다.
#codingdojing_maximize_CE
#각 부품의 성능을 오름차순으로 정렬
#현재의 가성비와, 추가부품의 가성비 (성능/추가가격)을 비교
#추가 부품의 가성비가 높으면 더한다.
original_price = eval(input('Original price of the machine: '))
original_perf = eval(input('Original performance of the machine: '))
addi_price = eval(input("Price of additional part: "))
addi_perf = list(map(int,input('Performance of additional parts: ').split())) #30 70 15 40 65
addi_perf.sort(reverse = True)
CE = original_perf / original_price
total_price = original_price
total_perf = original_perf
for i in range(len(addi_perf)):
if CE <= (addi_perf[i]/addi_price): #현재 가성비와 추가 가성비 비교
total_perf += addi_perf[i]
total_price += addi_price
CE = total_perf/total_price
else:
print(CE)
print(CE//1)
break
package justStudying;
import java.util.Arrays;
import java.util.Comparator;
public class test3_20210822 {
public static int sol(int orgPrice, int orgVal, int addPrice, Integer addVal[]) {
Double maxVal = orgVal / (double)orgPrice;
Arrays.sort(addVal, Comparator.reverseOrder());
Double temp = 0D;
for(int i=0; i<addVal.length; i++) {
// System.out.print(addVal[i] + " " + maxVal + " ");
temp = addVal[i] / (double)addPrice;
// System.out.println(temp);
if(maxVal < temp) {
orgPrice += addPrice;
orgVal += addVal[i];
maxVal = orgVal / (double)orgPrice;
}
}
return maxVal.intValue();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(sol(10,150,3,new Integer[]{30,70,15,40,65}));
}
}
def cost_performance(price, performance, add_price, add_performance):
a = []
for i in add_performance:
if ((performance / price) < ((performance+i) / (price+add_price))): # 부품을 추가했을 때 성능이 더 좋아졌다면
performance += i
price += add_price
a.append(i)
print(a)
return int(performance / price)
if __name__ == '__main__':
price = 10
performance = 150
add_price = 3
add_performance = [30,70,15,40,65]
print(cost_performance(price, performance, add_price, add_performance))
orig_price = 10
orig_perform=150
add_price =3
add_perform = [30,70,15,40,65]
pick =[]
def max_eff (price,perform) :
sum_price = orig_price
sum_perform = orig_perform
per = sorted(perform)
for k in range(len(per)):
sum_eff = sum_perform/sum_price
now_eff = (sum_perform+per[k])/(sum_price+price)
if now_eff>sum_eff:
sum_price +=price
sum_perform +=per[k]
pick.append(per[k])
return pick
a=max_eff(3,add_perform)
print("최고 가성비 조합은",a)
o_price = int(input("원래 기계의 가격 : "))
o_fun = int(input("원래 기계의 성능 : "))
add_price = int(input("추가 부품의 가격 : "))
add_fun = list(map(int,input("추가 부품의 성능 : ").split()))
cost_eff = [num for num in add_fun if num > sum(add_fun)/len(add_fun)]
cost_eff = (sum(cost_eff)+o_fun)/(o_price+add_price*len(cost_eff))
print("가성비: ",int(cost_eff))
# 가장 성능이 좋은 부품부터 추가로 더해가며 계산
machine = 150
parts = list(reversed(sorted([30, 70, 15, 40, 65])))
ability = [150/10]
for i in range(1,len(parts)+1):
ability.append((machine + sum(parts[0:i])) / (10 + 3*i))
print(int(max(ability)))
def calCostEffect(orV, orP, adV, adPs):
ce = int(orP//orV)
adPs = sorted(adPs, reverse=True)
for adP in adPs:
if ce < adP//adV:
return adP//adV
return -1
orV = 10
orP = 150
adV = 3
adPs = [30, 70, 15, 40, 65]
result = calCostEffect(orV, orP, adV, adPs)
if result:
print('추가 부품을 장착하여 얻을 수 있는 최대 가성비: ', result)
else:
print('추가 부품을 장착하여 얻을 수 있는 가성비가 없다')