C. Om Nom and Candies 巧妙优化枚举,将复杂度控制在10e6

时间:2022-10-05 17:55:51

                                    C. Om Nom and Candies

无线超大背包问题

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long LL;
const int INF=0x4fffffff;
const int EXP=1e-;
const int MS=;
const LL SIZE=; int main()
{
LL c,hr,hb,wr,wb;
cin>>c>>hr>>hb>>wr>>wb;
if(wb>wr)
{
swap(wb,wr);
swap(hb,hr);
} if(wr>SIZE) // 巧妙将 复杂度控制在 10e6
{
LL ans=0LL;
for(LL r=;r*wr<=c;r++)
{
LL b=(c-r*wr)/wb;
LL cur=r*hr+b*hb;
if(cur>ans)
ans=cur;
}
cout<<ans<<endl;
return ;
}
LL ans=;
LL h_big=max(wb*hr,wr*hb);
for(LL r=;r<wb;r++) // 如果r>=wb,可以组成一个公倍数重量的big
{
for(LL b=;b<wr;b++) // 同理
{
LL w=r*wr+b*wb;
if(w>c)
break;
LL big=(c-w)/(wr*wb);
LL cur=r*hr+b*hb+big*h_big;
if(cur>ans)
ans=cur;
}
}
cout<<ans<<endl;
return ;
}

    HDU 换了一个背景的同题      Zombie’s Treasure Chest

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long LL;
const int INF=0x4fffffff;
const int EXP=1e-;
const int MS=;
const LL SIZE=; int main()
{
int T,kase=;
scanf("%d",&T);
while(T--)
{
LL c,hr,hb,wr,wb;
//cin>>c>>hr>>hb>>wr>>wb;
cin>>c>>wr>>hr>>wb>>hb;
if(wb>wr)
{
swap(wb,wr);
swap(hb,hr);
} if(wr>SIZE) // 巧妙将 复杂度控制在 10e6
{
LL ans=0LL;
for(LL r=;r*wr<=c;r++)
{
LL b=(c-r*wr)/wb;
LL cur=r*hr+b*hb;
if(cur>ans)
ans=cur;
}
cout<<"Case #"<<kase++<<": "<<ans<<endl;
continue;
}
LL ans=;
LL h_big=max(wb*hr,wr*hb);
for(LL r=;r<wb;r++) // 如果r>=wb,可以组成一个公倍数重量的big
{
for(LL b=;b<wr;b++) // 同理
{
LL w=r*wr+b*wb;
if(w>c)
break;
LL big=(c-w)/(wr*wb);
LL cur=r*hr+b*hb+big*h_big;
if(cur>ans)
ans=cur;
}
}
cout<<"Case #"<<kase++<<": "<<ans<<endl;
}
return ;
}