P2983 [USACO10FEB]购买巧克力

P2983 [USACO10FEB]购买巧克力

题解

注意题目开 long long 

贪心策略:价格从低到高,买够为止

反证:若剩下的有一个K”,比K小,那么交换,稳赚不赔

           所以,在买K之前,所有比他便宜的都买完了

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<cstdlib>
#include<queue>

using namespace std;

#define ll long long

inline ll read()
{
    ll ans=0;
    char last=' ',ch=getchar();
    while(ch<'0'||ch>'9') last=ch,ch=getchar();
    while(ch>='0'&&ch<='9') ans=ans*10+ch-'0',ch=getchar();
    if(last=='-') ans=-ans;
    return ans;
}

ll n,b,ans=0;
struct node
{
    ll cost,cow;
}candy[100010];

bool cmp(node x,node y)
{
    return x.cost <y.cost ;
}

int main()
{
    
    n=read();b=read();
    for(ll i=1;i<=n;i++)
    {
        candy[i].cost =read();
        candy[i].cow =read();
    }
    
    sort(candy+1,candy+n+1,cmp);

    for(ll i=1;i<=n;i++)
    {
        if(candy[i].cow==0) continue;
        if(b==0)
        { printf("%lld",ans); return 0; }
        if(candy[i].cow <=b/candy[i].cost)  //直接乘起来会爆炸
        {
            b-=candy[i].cost *candy[i].cow;
            ans+=candy[i].cow;
            continue;
        }
        else
        {
            ans+=b/candy[i].cost;  //不要一个个枚举节省时间
            printf("%lld",ans); return 0;
        }
    }
    printf("%lld",ans);
    
    return 0;
}



 

猜你喜欢

转载自www.cnblogs.com/xiaoyezi-wink/p/11233782.html
今日推荐