Huawei OD Computer Test Algorithm Questions: Meals in the Canteen

Table of contents

Question part

Analysis and ideas

Code


Question part

topic Canteen serving meals
difficulty Disaster
Question description The employee canteen of a company provides meals in the form of lunch boxes. In order to reduce the queuing time for employees to get meals to 0, the canteen must serve meals quickly enough. Now it is necessary to calculate a minimum meal serving speed that can achieve a queuing time of 0 based on the statistical information of employees taking meals in the past. That is, the canteen must make at least how many box lunches per unit time to meet the requirements.
Enter description The first line is a positive integer N, indicating the opening time of the canteen. 1 <= N <= 1000.
The second line is a positive integer M, indicating the number of lunch boxes that have been prepared in the canteen before the meal. pi <= M <= 1000.
The third line contains N positive integers, separated by spaces, which in turn represent the number of people Pi who entered the canteen to get meals in chronological order per unit time during the meal period. 1 <=i<= N, 0<= Pi<=100.
Output description An integer, the minimum meal supply speed that can meet the requirements of the question (how many boxed lunches need to be made per unit time).
Additional information Only take one box lunch per person.
The queuing time needs to be 0, and it must be ensured that when the meal-picking employees arrive at the canteen, the number of lunch boxes in the canteen is no less than the number of people who come to pick up the meals this time.
Employees who come to pick up meals during the first unit of time can only pick up the lunch boxes prepared in the canteen before the meal starts.
The lunch boxes produced in each unit of time can only be supplied to employees who come to pick up meals in subsequent units of time.
The number of lunch boxes produced by the canteen per unit time is the same.
------------------------------------------
Example
Example 1
enter 3
14
10 4 5
output 3
illustrate In this example, there are a total of 3 batches of employees dining, with the number of people in each batch being 10, 4, and 5 respectively.
The canteen has 14 servings in stock before the meal starts.
 
The canteen must prepare at least 3 meals per unit of time to achieve the goal of zero queuing time. The specific situation is as follows:
The 10 employees who came in the first unit of time took their meals directly from the inventory. After picking up the meal, there are 4 lunch boxes left in stock, plus the 3 lunch boxes made in the first unit of time, there are 7 lunch boxes in stock.
The 4 employees who come in the second unit of time take 4 out of 7 copies from the inventory. After picking up the meal, there are 3 lunch boxes left in stock, plus the 3 lunch boxes made in the second unit of time, there are 6 lunch boxes in stock.
The employee who comes in the third unit of time takes 5 copies from the 6 copies in stock, and the stock is sufficient.
  
If the canteen can only make 2 meals per unit time, the situation is as follows: The
10 employees who come in the first unit time take their meals directly from the inventory. After picking up the meal, there are 4 lunch boxes left in stock, plus the 2 lunch boxes made in the first unit of time, there are 6 lunch boxes in stock.
The 4 employees who come in the second unit of time take 4 out of 6 copies from the inventory. After picking up the meal, there are 2 lunch boxes left in stock, plus the 2 lunch boxes made in the second unit of time, there are 4 lunch boxes in stock.
The employee who comes during the third unit of time needs to pick up 5 copies, but there are only 4 copies in stock, which is not enough stock.

Analysis and ideas

Question interpretation :

In this question, the first row is the total number of dining employees, set to count; the second row is the initial inventory number, set to stockQty; the third row is the number of copies of each batch, assuming that the number of each batch is placed In the array dinners, then the length of dinners is count, and dinners[i] is the number of copies required for the (i + 1)th batch (Note: the starting value of the batch is 1, placed at the 0th position in the array element).

Assume that the lowest meal supply speed in the question is x (x is a positive integer), then for all i (0 <= i <= count), x must satisfy (stockQty + x * i) >=   \sum_{idx=0}^{i} dinners[idx]. Among them,  \sum_{idx=0}^{i} dinners[idx] represents the sum of the first i elements of the dinners array, that is \sum_{idx=0}^{i} dinners[idx] = dinners[0] + dinners[1] + … + dinners[i].

Analysis ideas :

Although the difficulty of this question is set to "hard", the actual solution is relatively simple.

Set the initial value of x to 0.

According to the inequality (stockQty + x * i) >=   \sum_{idx=0}^{i} dinners[idx], for i, from 0 to (count -1), determine whether the current x value guarantees that the inequality is true:

  • If the inequality holds, no operation is performed;
  • If the inequality does not hold, that is, the value of x is too small, recalculate the value of x. After calculation, the new value of x must be greater than the old value.
    We know that when going from 0 to (i - 1), the old value of x can ensure that the inequality is established. When the value of x becomes larger, the left side of the inequality is larger than before. This means that when x takes on a new value (a larger value), this inequality must hold from 0 to ( i - 1 ).

After traversing, the calculated x is the value required by the question.

This algorithm only needs to traverse the dinners array once, and its time complexity is O(n); due to the use of auxiliary arrays, its space complexity is also O(n).


Code

Java code

import java.util.Scanner;

/**
 * 食堂供餐
 * 
 * @since 2023.09.13
 * @version 0.2
 * @author Frank
 *
 */
public class Dinners {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			// 第一行输入就餐的批次
			String strCount = sc.nextLine();
			int count = Integer.parseInt(strCount);
			// 第二行输入初始库存数
			String strStockQty = sc.nextLine();
			int stockQty = Integer.parseInt(strStockQty);
			// 第三行输入每批次所需的午餐份数
			// 此处dinners中的元素都是String,后面需要转换成int处理
			String strDinners = sc.nextLine();
			String[] dinners = strDinners.split(" "); // dinners.length == count

			processDinners(count, stockQty, dinners);
		}
	}

	private static void processDinners(int count, int stockQty, String[] dinners) {
		int currentSumNeeded = 0;
		int x = 0;
		int currentStock = stockQty;
		for (int i = 0; i < count; i++) {
			currentStock = stockQty + i * x;
			currentSumNeeded += Integer.parseInt(dinners[i]);
			if (currentStock < currentSumNeeded) {
				// 计算最小的 x(新值必定比当前的x大),确保 currentStock >= currentSumNeeded
				int diff = currentSumNeeded - stockQty;
				int tmpX = diff / i;
				if (diff % i != 0) {
					tmpX++;
				}
				x = tmpX;
			}
		}
		System.out.println(x);
	}
}

JavaScript code

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function() {
    while (line = await readline()) {
        // 第一行,进餐的批次
        var count = parseInt(line);
        // 第二行,初始库存数
        var strStockQty = await readline();
        var stockQty = parseInt(strStockQty);
        // 第三行,每批次需要的份数
        var initDinners = await readline();
        var strDinners = initDinners.split(" ");

        processDinners(count, stockQty, strDinners);
    }
}();

function processDinners(count, stockQty, strDinners) {
    var currentSumNeeded = 0;
    var x = 0;
    var currentStock = stockQty;
    for (var i = 0; i < count; i++) {
        currentStock = stockQty + i * x;
        currentSumNeeded += parseInt(strDinners[i]);
        if (currentStock < currentSumNeeded) {
            // 计算最小的 x(新值必定比当前的x大),确保 currentStock >= currentSumNeeded
            var diff = currentSumNeeded - stockQty;
            var tmpX = parseInt(diff / i);
            if (diff % i != 0) {
                tmpX++;
            }
            x = tmpX;
        }
    }
    console.log(x);
}

(over)

Guess you like

Origin blog.csdn.net/ZiJinShi/article/details/132677015