最大额度购买商品
一共有n元钱,购买a、b、c、d、e几种商品,单价分别为a1、b1、c1、d1、e1。可以只单独购买其中一种或几种商品,怎么实现购买后余下的金额最小? #include <stdio.h>#include <string.h>
double sum(const double data[], size_t size) {
double result = 0;
for(size_t i = 0; i < size; ++i) {
result += data;
}
return result;
}
void enum_all(const double data[], double buff[], size_t size, size_t index, double target, double result[], size_t *result_size) {
double current_sum = sum(buff, index);
if(current_sum > target) {
current_sum -= buff[--index];
double result_sum = sum(result, *result_size);
if(current_sum > result_sum) {
*result_size = index;
memcpy(result, buff, sizeof(double) * *result_size);
}
return;
}
for(size_t i = 0; i < size; ++i) {
buff = data;
enum_all(data, buff, size, index + 1, target, result, result_size);
}
}
int main(void) {
//double price = {1.2, 2.3, 3.4, 4.5, 5.6};
double price = {1.2, 2.3, 2.6, 4.5, 5.6};
//double price = {1.2, 2.3, 2.7, 8.1, 5.6};
double buff;
double result;
size_t size = 0;
enum_all(price, buff, 5, 0, 10, result, &size);
for(size_t i = 0; i < size; ++i) {
printf("%lf ", result);
}
puts("");
printf("sum: %lf\n", sum(result, size));
return 0;
}
页:
[1]