# 贪心法——乘船问题

## 乘船问题实现算法

// 贪心法
// 乘船问题
void boat(float *a, int n, float C) {
sort(a, a + n);
int i = 0;
int j = n - 1;
int boatSum = 0;
while(i <= j) {

if(i == j) {
cout << "组合为：" << a[i] << endl;
boatSum++;
break;
}

if(a[i] + a[j] <= C) {
cout << "组合为：" << a[i] << " " << a[j] << endl;
boatSum++;
i++;
j--;
} else {
cout << "组合为：" << a[j] << endl;
boatSum++;
j--;
}
}
}

## 测试主程序

#include <iostream>
#include <algorithm>

using namespace std;

// 贪心法
// 乘船问题
void boat(float *a, int n, float C) {
sort(a, a + n);
int i = 0;
int j = n - 1;
int boatSum = 0;
while(i <= j) {

if(i == j) {
cout << "组合为：" << a[i] << endl;
boatSum++;
break;
}

if(a[i] + a[j] <= C) {
cout << "组合为：" << a[i] << " " << a[j] << endl;
boatSum++;
i++;
j--;
} else {
cout << "组合为：" << a[j] << endl;
boatSum++;
j--;
}
}
}

int main() {
while(true) {
// n个人
int n;
cout << "请输入人的总数(0退出)：";
cin >> n;
if(!n) {
break;
}
float C;
cout << "请输入船的最大载重量：";
cin >> C;
float a[n];
for(int i = 0; i < n; i++) {
cout << "第" << i + 1 << "个人的重量为：";
cin >> a[i];
}

cout << "使用最少船的组合和总船数为：" << endl;
boat(a, n, C);
}
return 0;
}

## 输出数据

请输入人的总数(0退出)：5

Process returned 0 (0x0)   execution time : 14.700 s
Press any key to continue.

11-15 1374

08-18 423

12-15 213

08-03 286

01-20 778

03-31 1653

05-09 487

11-21 510

11-20 252

04-24 255