إجابة سؤال الموز Warhouse


المستودع، والذي يسمى بعبارة أخرى المستودع، هو مبنى يستخدم لتخزين المواد الخام أو البضائع المصنعة حتى يتم تصديرها إلى أماكن أخرى.

هناك عدد من المنافذ التي تستخدم لتخزين وإنضاج كمية كبيرة من الموز. بمجرد أن ينضج الموز، سيقوم كل صاحب مزرعة بتعبئة كل هذا الموز كوحدة واحدة ونقله إلى المطار لتصديره إلى بلدان أخرى. كل هذه الآلهة قريبة من بعضها البعض وأصحابها ودودون. لذلك، أثناء نقل الموز، يرغبون في مشاركة السيارة (إن أمكن) لتقليل تكلفة النقل. ولكن يمكن لشخصين فقط مشاركة السيارة ويمكن لكل مركبة أن تحمل وزن “ث” طن في المرة الواحدة.

بمعرفة مصفوفة تمثل أوزان الموز لكل مالك، والحد الأقصى الذي يمكن للمركبة استيعابه، أوجد أقل عدد من المركبات اللازمة لنقل جميع الموز إلى المطار.
ملحوظة: لا توجد أحمال أثقل من الحد المحدد.
يتم قياس وزن الموز بالطن.

ما حاولت:

الحصول على إجابة خاطئة للرمز

ج
#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

يجب عليك تنظيف وتصحيح التعليمات البرمجية الخاصة بك. ابدأ بتفاعل المستخدم المحسّن.

سي ++
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]);
    }

من الأفضل استخدام بعض البنية في التعليمات البرمجية الخاصة بك لتحسين إمكانية القراءة، كما هو الحال بالنسبة للمركبة

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

تحقيق المزيد من الناتج، كما هو الحال في المقارنة.

زيارة بعض تعلم البرنامج التعليمي C لتحل واجبك.

コメント

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