C. Om Nom and Candies 巧妙优化枚举,将复杂度控制在10e6
无线超大背包问题
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <string> 7 #include <vector> 8 #include <set> 9 #include <map> 10 #include <stack> 11 #include <queue> 12 #include <sstream> 13 #include <iomanip> 14 using namespace std; 15 typedef long long LL; 16 const int INF=0x4fffffff; 17 const int EXP=1e-5; 18 const int MS=12; 19 const LL SIZE=1000; 20 21 int main() 22 { 23 LL c,hr,hb,wr,wb; 24 cin>>c>>hr>>hb>>wr>>wb; 25 if(wb>wr) 26 { 27 swap(wb,wr); 28 swap(hb,hr); 29 } 30 31 if(wr>SIZE) // 巧妙将 复杂度控制在 10e6 32 { 33 LL ans=0LL; 34 for(LL r=0;r*wr<=c;r++) 35 { 36 LL b=(c-r*wr)/wb; 37 LL cur=r*hr+b*hb; 38 if(cur>ans) 39 ans=cur; 40 } 41 cout<<ans<<endl; 42 return 0; 43 } 44 LL ans=0; 45 LL h_big=max(wb*hr,wr*hb); 46 for(LL r=0;r<wb;r++) // 如果r>=wb,可以组成一个公倍数重量的big 47 { 48 for(LL b=0;b<wr;b++) // 同理 49 { 50 LL w=r*wr+b*wb; 51 if(w>c) 52 break; 53 LL big=(c-w)/(wr*wb); 54 LL cur=r*hr+b*hb+big*h_big; 55 if(cur>ans) 56 ans=cur; 57 } 58 } 59 cout<<ans<<endl; 60 return 0; 61 }
HDU 换了一个背景的同题 Zombie’s Treasure Chest
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <string> 7 #include <vector> 8 #include <set> 9 #include <map> 10 #include <stack> 11 #include <queue> 12 #include <sstream> 13 #include <iomanip> 14 using namespace std; 15 typedef long long LL; 16 const int INF=0x4fffffff; 17 const int EXP=1e-5; 18 const int MS=12; 19 const LL SIZE=1000; 20 21 int main() 22 { 23 int T,kase=1; 24 scanf("%d",&T); 25 while(T--) 26 { 27 LL c,hr,hb,wr,wb; 28 //cin>>c>>hr>>hb>>wr>>wb; 29 cin>>c>>wr>>hr>>wb>>hb; 30 if(wb>wr) 31 { 32 swap(wb,wr); 33 swap(hb,hr); 34 } 35 36 if(wr>SIZE) // 巧妙将 复杂度控制在 10e6 37 { 38 LL ans=0LL; 39 for(LL r=0;r*wr<=c;r++) 40 { 41 LL b=(c-r*wr)/wb; 42 LL cur=r*hr+b*hb; 43 if(cur>ans) 44 ans=cur; 45 } 46 cout<<"Case #"<<kase++<<": "<<ans<<endl; 47 continue; 48 } 49 LL ans=0; 50 LL h_big=max(wb*hr,wr*hb); 51 for(LL r=0;r<wb;r++) // 如果r>=wb,可以组成一个公倍数重量的big 52 { 53 for(LL b=0;b<wr;b++) // 同理 54 { 55 LL w=r*wr+b*wb; 56 if(w>c) 57 break; 58 LL big=(c-w)/(wr*wb); 59 LL cur=r*hr+b*hb+big*h_big; 60 if(cur>ans) 61 ans=cur; 62 } 63 } 64 cout<<"Case #"<<kase++<<": "<<ans<<endl; 65 } 66 return 0; 67 }