Codeforces Hamburgers(二分查找)

在這裏插入圖片描述
題目大意:
做一個漢堡需要b,s,c三種材料,一開始每種材料有nb,ns,nc個,且它們的單件價格分別爲pb,ps,pc,有r塊錢,根據配方,問最多能做多少個漢堡

解題思路:
考慮用二分查找,注意邊界條件,最後所用的錢數可以不是剛剛好爲r

代碼:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll rn,ans;
int b,s,c,nb,ns,nc,pb,ps,pc;
int main()
{
    string temp;
    cin>>temp;
    for(auto v:temp)
    {
        if(v=='B') b++;
        else if(v=='S') s++;
        else c++;
    }
    cin>>nb>>ns>>nc;
    cin>>pb>>ps>>pc;
    cin>>rn;
    ll l=0,r=0x3f3f3f3f3f3f;
    while(l<=r)
    {
        ll mid=(l+r)/2;
        ll n1=mid*b-nb,n2=mid*s-ns,n3=mid*c-nc;
        if(n1<0) n1=0;
        if(n2<0) n2=0;
        if(n3<0) n3=0;
        ll p=n1*pb+n2*ps+n3*pc;
        if(rn>=p)
        {
            ans=mid;
            l=mid+1;
        }
        else r=mid-1;
    }
    cout<<ans<<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章