【解決方法】仓库香蕉问题解答

编程


仓库,即仓库,是用于储存原材料或制成品直至出口到其他地方的建筑物。

有n个仓库,用于储存和催熟大量的香蕉。 一旦香蕉成熟,每个仓库老板都会将所有香蕉打包并运输到机场,然后出口到其他国家。 所有这些仓库都彼此靠近,业主也很友善。 因此,在运输香蕉时,他们希望共用车辆(如果可能的话),以降低运输成本。 但只能两人共用一辆车,每辆车一次可承载“w”吨的重量。

给定一个代表每个所有者香蕉重量的数组,以及车辆可以容纳的最大限制,找到将所有香蕉运输到机场所需的最少车辆数量。
注意:没有超过给定限制的负载。
香蕉的重量以吨为单位。

我尝试过的:

得到错误的代码答案

C
#include <stdio.h>
#include <stdlib.h>

void clearInputBuffer() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

int compare(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

int minVehicles(int arr[], int n, int capacity) {
    // Sort the array in non-decreasing order
    qsort(arr, n, sizeof(int), compare);

    // Use two pointers approach to count the number of vehicles needed
    int count = 0;
    int i = 0;
    int j = n - 1;
    while (i <= j) {
        // If the sum of the current pair is less than or equal to the capacity, load both items
        if (arr[i] + arr[j] <= capacity) {
            i++;
            j--;
        } else {
            // If not, load the heavier item in a separate vehicle
            j--;
        }
        count++;
    }

    return count;
}

int main() {
    int n, capacity;
    printf("Enter the weights of the items separated by space: ");
    
    // Read the weights of the items in a single line
    scanf("%d", &n);
    int *arr = (int *)malloc(n * sizeof(int));

    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    clearInputBuffer(); // Clear the input buffer

    printf("Enter the capacity of each vehicle: ");
    scanf("%d", &capacity);

    int result = minVehicles(arr, n, capacity);

    printf("Minimum number of vehicles required: %d\n", result);

    free(arr);

    return 0;
}

解决方案2

您必须清理并调试您的代码。 从改进用户交互开始。

C++
int main() {
    int n, capacity;
    printf("Enter the count of the items: ");
    
    // Read the weights of the items in a single line
    scanf("%d", &n);
    int *arr = (int *)malloc(n * sizeof(int));

    for (int i = 0; i < n; i++) {
        printf("Enter the weights of the item %d separated by space: ", i);
        scanf("%d", &arr[i]);
    }

您最好在代码中使用一些结构以获得更好的可读性,例如车辆

C++
struct Vehicle {
 int identifier; // like index
 int maxLoad;
 int currentLoad;
}

进行更多输出,如比较中所示。

参观一些 学习C教程 解决 你的家庭作业

コメント

タイトルとURLをコピーしました