贪心算法-实验: 最优装载问题
一、实验目的
1. 掌握各类数据结构的操作;
2. 掌握用c++语言描述与实现算法的方法;
3. 理解算法的概念,掌握算法复杂度分析技术;
二、实验内容
1. 运用C或C++语言,按要求完成算法实现;
2. 对所设计的算法采用大O符号进行时间复杂性分析;
三、实验任务
设有重量为(4,6,3,5,7,2,9)的7个集装箱,轮船的载重为26,求能够装载的集装箱的最大 数量?
首先,我们需要将集装箱按重量升序排序。然后,我们从最轻的集装箱开始,依次尝试将集装箱装入轮船,直到达到轮船的载重限制为止。最后,我们返回能够装载的集装箱数量。
在代码中,我们可以使用数组来存储集装箱的重量,然后使用 `qsort` 函数对数组进行排序。接着,我们遍历排序后的集装箱数组,尝试将集装箱装入轮船,直到达到载重限制为止。最后,我们返回能够装载的集装箱数量。
//当然,下面是使用 C 语言实现最优装载问题的示例代码:
//c
#include <stdio.h>
#include <stdlib.h>
// 比较函数用于
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int maxContainers(int shipCapacity, int weights[], int n) {
qsort(weights, n, sizeof(int), compare); // 按重量升序排序
int count = 0;
int currentWeight = 0;
for (int i = 0; i < n; i++) {
if (currentWeight + weights[i] <= shipCapacity) {
currentWeight += weights[i];
count++;
} else {
break;
}
}
return count;
}
int main() {
int weights[] = {4, 6, 3, 5, 7, 2, 9};
int shipCapacity = 26;
int n = sizeof(weights) / sizeof(weights[0]);
int maxContainersCount = maxContainers(shipCapacity, weights, n);
printf("最大能够装载的集装箱数量为: %d\n", maxContainersCount);
return 0;
}
//在这个示例中,我们使用了标准库函数 `qsort` 来对集装箱按重量进行升序排序。