Codeforces C - Om Nom and Candies
思路:贪心+思维(或者叫数学)。假设最大值max(wr,wb)为wr,当c/wr小于√c时,可以枚举r糖的数量(从0到c/wr),更新答案,复杂度√c;否则,假设hr/wr<hb/wr,得到hr*wb<hb*wr,由这个等式可知,在有wb*wr重量限制的情况下,买wb个r糖没有买wr个b糖划算,当需要买超过wb个r糖时,不如去买b糖,可以枚举r糖的数量(从0到wb-1),更新答案,复杂度√c。
代码:
#include<bits/stdc++.h> using namespace std; #define ll long long const int N=1e5+5; const int INF=0x3f3f3f3f; int main() { ll c,hr,hb,wr,wb; cin>>c>>hr>>hb>>wr>>wb; if(wr<=wb)swap(wr,wb),swap(hr,hb); ll n=c/wr; ll ans=0; if(n<=sqrt(c)) { for(ll i=0;i<=n;i++) { ll temp=c-i*wr; ll j=temp/wb; ans=max(ans,(ll)i*hr+(ll)j*hb); } } else { if(hr*wb>=hb*wr)swap(wr,wb),swap(hr,hb); for(ll i=0;i<wb;i++) { ll temp=c-i*wr; ll j=temp/wb; ans=max(ans,i*hr+j*hb); } } cout<<ans<<endl; return 0; }