[51Nod](1432)独木舟 ---- 贪心

n个人,已知每个人体重。独木舟承重固定,每只独木舟最多坐两个人,可以坐一个人或者两个人。显然要求总重量不超过独木舟承重,假设每个人体重也不超过独木舟承重,问最少需要几只独木舟?
Input
第一行包含两个正整数n (0 < n<=10000)和m (0< m< =2000000000),表示人数和独木舟的承重。
接下来n行,每行一个正整数,表示每个人的体重。体重不超过1000000000,并且每个人的体重不超过m。

Output

一行一个整数表示最少需要的独木舟数。

Input示例

3 6
1
2
3

Output示例

2

思路:
先把所有人的重量从小到大排序,然后尽量让重量最大的带一个重量最小的,如果带不了,那么重量最大的独占一个船。

AC代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4+5;
int w[maxn];
int n,m;
int main()
{
    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    #endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    cin>>n>>m;
    for(int i=0;i<n;i++)
        cin>>w[i];
    sort(w,w+n);
    int l = 0, r = n-1;
    int ans = 0;
    while(l<=r)
    {
        if(w[l]+w[r]<=m)
        {
            l++;
            r--;
            ans++;
        }
        else if(w[l]+w[r]>m && w[r]<=m)
        {
            r--;
            ans++;
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37624640/article/details/79940145
今日推荐