P14635 糖果店 题解

· · 题解

一个简单的贪心做法,不需要二分

我们可以将购入分为买第奇数个和第偶数个两种情况,并且满足 奇数颗个数=偶数颗个数 或 偶数颗个数+1。不难想到分为两组:

同时,由于不考虑糖的种类,我们发现:买单价便宜(性价比高)的总是最优的。这个贪心策略是显然的(至于为什么在T2相同的策略是错的,因为T2会有权值影响)
因此,把糖果按照单价排个序,逐个判断能不能购买、买多少个,即可通过此题
时间复杂度 O(n \log n)

注意:要开long long!我考场上的代码计算的buy没开long long于是喜提90,让本就不高的分数雪上加霜……

代码(能通过民间数据和工单里的一组Hack数据):

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

struct Candy{
    int single_price;
    bool has_two;
}candies[200020];

ll n,m,x,y,ans;
bool cmp(Candy &a, Candy &b){
    return a.single_price<b.single_price;
}

int main(){
    cin>>n>>m;
    m*=2; // 为了规避浮点数运算,给所有钱相关变量都乘二
    for(int i=0;i<n;i++){
        cin>>x>>y;
        candies[i*2].single_price=x*2; // 原始为x
        candies[i*2].has_two=0;
        candies[i*2+1].single_price=x+y; // 原始为(x+y)/2
        candies[i*2+1].has_two=1;
    }
    sort(candies,candies+n*2,cmp);
    for(int i=0;i<2*n;i++){
        if(candies[i].has_two){
            ll buy = m/candies[i].single_price/2;
            ans+=buy*2;
            m-=buy*candies[i].single_price*2;
        }else{
            if(candies[i].single_price<=m){
                m-=candies[i].single_price;
                ans+=1;
            }else{
                break;
            }
        }
    }
    cout<<ans;
    return 0;
}