#include <stdio.h>
#include <limits.h> // 用于INT_MAX
int minCost(int n, int x, int prices[]) {
int minCost = INT_MAX; // 初始化最小花费为最大整数值
int totalCost, i, j;
int state, bitMask; // state用于遍历所有组合,bitMask用于检查某一位是否被设置
// 遍历所有可能的购书组合
for (state = 0; state < (1 << n); state++) {
totalCost = 0;
for (i = 0; i < n; i++) {
// 检查第i本书是否被选中(即state的第i位是否为1)
bitMask = 1 << i;
if (state & bitMask) {
totalCost += prices[i]; // 如果选中,则累加价格
}
}
// 如果当前组合的总价格大于等于x,且比之前记录的最小花费小,则更新最小花费
if (totalCost >= x && totalCost < minCost) {
minCost = totalCost;
}
}
return minCost;
}
int main() {
int n, x, i;
int prices[30]; // 假设最多30本书
// 读取输入
scanf("%d %d", &n, &x);
for (i = 0; i < n; i++) {
scanf("%d", &prices[i]);
}
// 调用函数并输出结果
int result = minCost(n, x, prices);
printf("%d\n", result);
return 0;
}
标签:totalCost,组合,int,次种,minCost,bitMask,state,prices From: https://blog.csdn.net/2303_80757919/article/details/137018064