1. 程式人生 > >Codeforces C - Om Nom and Candies

Codeforces C - Om Nom and Candies

end pro name color ron cin urn 復雜度 define

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; }

Codeforces C - Om Nom and Candies