独木舟 51Nod - 1432 (贪心)

https://vjudge.net/problem/51Nod-1432

很明显的贪心算法, 如果能带最小的走则带走, 否则自己走即可

开始那道题的时候有一个误区, 总想着能够要带能带走的最大的走, 这个其实无所谓, 因为一条船只能坐两个人, 只要坐上两个人就算是值得了, 不考虑空间问题. 而如果我这样写就又会变成n^2复杂度

//独木舟 贪心
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(n));
typedef  long long LL;
const LL maxn = 1e9+10;

int n, m;
vector<int> p;
bool cmp(int a, int b)
{
    return a > b;
}
int main()
{
    int sum = 0, input;
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        cin >> input;
        p.push_back(input);
    }
    sort(p.begin(), p.end(), cmp);

    while(!p.empty()){
        if(p.size() == 1){ //只剩一个人
            sum++;
            break;
        }
        int maxW = p.front(), minW = p.back(); //每次都让最重的人上
        p.erase(p.begin());
        if(maxW + minW > m){ //只能自己坐一条船
            sum++;
            continue;
        }
        else{   //否则带最小的走
            sum++;
            p.pop_back();
        }
    }
    cout << sum << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/83154056
今日推荐