如何找到n个人的最佳汽车数量?

问题描述 投票:4回答:2

有一套车

{
 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;
algorithm
2个回答
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>

Time Complexity

没有重复模式优化,这将在O(人*车)时间运行。当包含该优化时,它在O(LCM(座位)*汽车)中运行,变得独立于人数。


0
投票

你的问题实际上只是Knapsack problem。你只需要考虑负权重/容量。通过这样做,您的最小化问题将成为最大化问题。获得最佳解决方案的最佳方法是使用动态编程,您可以在这里找到一个示例:https://www.geeksforgeeks.org/knapsack-problem/

© www.soinside.com 2019 - 2024. All rights reserved.