23 救生艇
1.问题描述
第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
示例 1:
输入:people = [1,2], limit = 3
输出:1
解释:1 艘船载 (1, 2)
示例 2:
输入:people = [3,2,2,1], limit = 3
输出:3
解释:3 艘船分别载 (1, 2), (2) 和 (3)
示例 3:
输入:people = [3,5,3,4], limit = 5
输出:4
解释:4 艘船分别载 (3), (3), (4), (5)
2.输入说明
首先输入人的数量n,然后输入n个整数,表示人的体重。
最后输入limit。
1 <= n <= 50000
1 <= 人的体重 <= limit <= 30000
3.输出说明
输出一个整数
4.范例
输入
4
3 5 3 4
5
输出
4
5.代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(vector<int>a, vector<int>b)
{
return a < b;
}
int num_boat(vector<int> people,int limit)
{
//原解法错误案例
//输入
//4
//5 1 4 2
//6
//输出
//2
//但是该算法输出3,说明只是利用sort进行排序会导致错误
/*
int res = 0;
int n = people.size();//总人数
sort(people.begin(), people.begin()+n,less<int>());
for (int i = 0; i < n - 1; i+=2)
{
if (people[i + 1] + people[i] <= limit)
{
n -= 2;
res++;
}
}
res += n;
return res;*/
//正确解法
int ans = 0;
sort(people.begin(), people.end());
int slim = 0;
int fat = people.size() - 1;
//思想:考虑体重最轻的和最重的人能不能同乘一条船,如果可以,就将这两人从原问题中删去;若不能,最胖的必须单独乘一条船
//然后看最轻的和第二胖的那个能否乘同一条船
while (slim <= fat)
{
if (people[slim] + people[fat] <= limit)
{
slim++;
fat--;
ans++;
}
else
{
fat--;
ans++;
}
}
return ans;
}
int main()
{
int n, data,limit;
vector<int> people;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> data;
people.push_back(data);
}
cin >> limit;
int res = num_boat(people,limit);
cout << res;
return 0;
}