有一套车
{
3: 1
4: 1.4
8: 2.2
}
其中钥匙是汽车容量,价值是价格系数。
对于很多人来说,我们应该找到一组汽车,而价格系数的总和应该尽可能低。 例如,对于7个人来说,使用一辆容量= 8的汽车是合理的。 对于9个人来说,拥有一个8人帽是没问题的。和一个3帽。辆。
构成最佳汽车组的算法是什么?容量和系数在实际使用中可能不同,因此依赖于此处给出的数据非常重要。谢谢!
UPD。这里有一段代码构建了一系列没有效率因素的汽车 /希望可能的汽车变种不估计3 :
let carSet = {},
peopleFree = 123456,
cars =
[
{capacity: 3, coefficient: 1},
{capacity: 4, coefficient: 1.4},
{capacity: 3, coefficient: 2.2},
],
minCapacity = 0,
maxCapacity = 0;
_.forEach(cars, (car) => {
if (car['capacity'] >= maxCapacity) { //find max capacity
maxCapacity = car['capacity'];
}
if (car['capacity'] <= maxCapacity) { //find min capacity
minCapacity = car['capacity'];
}
carSet[car['capacity']] = 0; //create available set of capacities
});
_.forEach(cars, (car) => {
if (peopleFree <= 0) //all people are assigned. stopping here
return;
if (peopleFree <= minCapacity) { //if people quantity left are equal to the min car, we assign them
carSet[minCapacity] += 1;
peopleFree = 0;
return;
}
let currentCapacityCars = Math.floor(peopleFree / car['capacity']);
peopleFree = peopleFree % car['capacity'];
carSet[car['capacity']] = currentCapacityCars;
if (peopleFree && car['capacity'] == minCapacity) {
carSet[minCapacity] += 1;
}
});
return carSet;
答案 0 :(得分:3)
您可以使用动态编程技术:
对于一定数量的人来说,看看一个人的最佳解决方案是否会产生空座位。如果是这样,那个配置对于另外一个人来说也是最好的。
如果没有,请选择一辆车,让尽可能多的人坐在其中,看看剩余人数的最佳解决方案是什么。将最佳解决方案的总价格与所选汽车的总价格相结合。对所有类型的汽车重复此操作,并以收益率最低的价格购买。
还有另一种可能的优化:当创建长序列(为越来越多的人分配)时,一种模式开始出现,一遍又一遍地重复。因此,当人数很多时,我们可以将结果用于少数人,在模式中以相同的“偏移”,然后添加两个后续模式块之间的恒定差异的汽车数量。我的印象是,当达到座位数的最小公倍数时,保证重复模式。我们应该采取这种模式的第二块,因为当我们只有少数人(1或2 ......)时,我们不能填充汽车这一事实会扭曲第一块。这种情况不会重演。以3座,4座和8座座位的汽车为例。 LCM是24.有一个保证模式将从24人开始重复:它重复48人,72,......等。 (它可能会更频繁地重复,但至少它会以大小= LCM的块重复)
您可以使用自上而下或自下而上的方法实施DP算法。我在这里实现了自下而上,从为一个人,两个人,等等计算最佳解决方案开始,直到达到所需的人数,始终保持所有以前的结果,所以他们不需要计算两次:
function minimize(cars, people) {
// Convert cars object into array of objects to facilitate rest of code
cars = Object.entries(cars)
.map(([seats, price]) => ({ seats: +seats, price }));
// Calculate Least Common Multiple of the number of seats:
const chunk = lcm(...cars.map( ({seats}) => seats ));
// Create array that will have the DP best result for an increasing
// number of people (index in the array).
const memo = [{
carCounts: Array(cars.length).fill(0),
price: 0,
freeSeats: 0
}];
// Use DP technique to find best solution for more and more people,
// but stop when we have found all results for the repeating pattern.
for (let i = 1, until = Math.min(chunk*2, people); i <= until; i++) {
if (memo[i-1].freeSeats) {
// Use same configuration as there is still a seat available
memo[i] = Object.assign({}, memo[i-1]);
memo[i].freeSeats--;
} else {
// Choose a car, place as many as possible people in it,
// and see what the best solution is for the remaining people.
// Then see which car choice gives best result.
const best = cars.reduce( (best, car, seq) => {
const other = memo[Math.max(0, i - car.seats)],
price = car.price + other.price;
return price < best.price ? { price, car, other, seq } : best;
}, { price: Infinity } );
memo[i] = {
carCounts: best.other.carCounts.slice(),
price: best.price,
freeSeats: best.other.freeSeats + Math.max(0, best.car.seats - i)
};
memo[i].carCounts[best.seq]++;
}
}
let result;
if (people > 2 * chunk) { // Use the fact that there is a repeating pattern
const times = Math.floor(people / chunk) - 1;
// Take the solution from the second chunk and add the difference in counts
// when one more chunk of people are added, multiplied by the number of chunks:
result = memo[chunk + people % chunk].carCounts.map( (count, seq) =>
count + times * (memo[2*chunk].carCounts[seq] - memo[chunk].carCounts[seq])
);
} else {
result = memo[people].carCounts;
}
// Format result in Object key/value pairs:
return Object.assign(...result
.map( (count, seq) => ({ [cars[seq].seats]: count })));
}
function lcm(a, b, ...args) {
return b === undefined ? a : lcm(a * b / gcd(a, b), ...args);
}
function gcd(a, b, ...args) {
if (b === undefined) return a;
while (a) {
[b, a] = [a, b % a];
}
return gcd(b, ...args);
}
// I/O management
function processInput() {
let cars;
try {
cars = JSON.parse(inpCars.value);
} catch(e) {
preOut.textContent = 'Invalid JSON';
return;
}
const result = minimize(cars, +inpPeople.value);
preOut.textContent = JSON.stringify(result);
}
inpPeople.oninput = inpCars.oninput = processInput;
processInput();
Car definition (enter as JSON):
<input id="inpCars" value='{ "3": 1, "4": 1.4, "8": 2.2 }' style="width:100%"><p>
People: <input id="inpPeople" type="number" value="13" min="0" style="width:6em"><p>
Optimal Car Assignment (lowest price):
<pre id="preOut"></pre>
如果没有重复模式优化,则会在 O(人*车)时间内运行。当包含该优化时,它将在 O(LCM(座位)*汽车)中运行,从而与人数无关。
答案 1 :(得分:0)
你的问题实际上只是Knapsack problem。你只需要考虑负权重/容量。通过这样做,您的最小化问题将成为最大化问题。获得最佳解决方案的最佳方法是使用动态编程,您可以在此处找到示例: https://www.geeksforgeeks.org/knapsack-problem/