独木舟

· · 个人记录

题目描述

旅行社计划组织一个独木舟旅行,租用的独木舟都是一样的,最多乘两人,而且载重有一个限度。

现在要节约费用,所以要尽可能地租用最少的舟。

本题的任务是读入独木舟的载重量,参加旅行的人数以及每个人的体重,计算出所需要的独木舟数目。

输入格式

第 1 行是 w(80≤w≤200),表示每条独木舟最大的载重量。

第 2 行是正整数 n(1≤n≤30000),表示参加旅行的人数。

接下来的 n 行,每行是一个正整数 ti(5≤ti≤w),表示每个人的重量。

输出格式

输出一行一个数,表示最少的独木舟数目。

样例输入

100
9
90
20
20
30
50
60
70
80
90

样例输出

6

解法

本题需要使用贪心算法

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;

const int NR = 3e4 + 10;
int a[NR];
bool flag[NR];//用flag[i]标记编号为i的人有没有独木舟坐 

int main()
{ 
    //输入 
    int w, n;
    cin >> w >> n;
    for(int i = 1; i <= n; i++)
        cin >> a[i];
    sort(a + 1, a + 1 + n);//用sort排序 
    //贪心 
    int cnt = 0;//用cnt标记独木舟的数量 
    for(int i = 1; i <= n; i++)
    {
        if(flag[i] == true) continue; //只给没有独木舟的人安排 
        cnt++;
        flag[i] = true;//标记已有 
        for(int j = n; j > i; j--)//i越小,j越大 
        {
            if(flag[j] == false && a[i] + a[j] <= w) //先要确定j没有独木舟 
            {
                flag[j] = true;//将j标记已有 
                break;
            }
        }
    }
    //输出 
    cout << cnt;
    return 0;
}

总结

这道题比较简单,要注意 j 为 n~i+1