Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- bool BestApprox(int BoxSizes[],int dim,int Approx1[],int Approx2[],int n){
- int res1=0,res2=0;
- for (int i=0;i<dim;i++){
- res1+=Approx1[i]*BoxSizes[i];
- res2+=Approx2[i]*BoxSizes[i];
- }
- if (res1>n) return false;
- return res1>res2;
- }
- bool FillBoxes( //returns true if n items perfectly fits int the boxes
- int BoxSizes[], //an array containing the box sizes
- int dim, //the dimension of the array BoxSizes
- int Used[], //an array of size dim that will be filled with the number of boxes used. if the function returns false this contains junk
- int Approx[], //an array of size dim that will be filled with the number of boxes used that best approximates the number of items (it will be equal to Used if the fit is perfect)
- int n //number of items to divide in boxes
- ){
- int temp=0;
- for (int i=0;i<dim;i++) temp+=Used[i]*BoxSizes[i];
- if (n-temp<0) return false;
- for (int i=0;i<dim;i++){
- if((n-temp)%BoxSizes[i]==0){
- Used[i]+=(n-temp)/BoxSizes[i];
- Approx=Used;
- return true;
- }
- }
- for (int i=0;i<dim;i++){
- Used[i]+=1;
- if(FillBoxes(BoxSizes,dim,Used,Approx,n)) return true;
- if (BestApprox(BoxSizes,dim,Used,Approx,n)){
- for (int i=0;i<dim;i++) Approx[i]=Used[i];
- }
- Used[i]-=1;
- }
- return false;
- }
- int main(){
- int Sizes[3]={20,9,6}; //sizes of the nuggets containers
- int BoxCombination[3]={0,0,0}; //array of zeros that will be filled with the solution
- int BoxApprox[3]={0,0,0}; //array of zeros that will be filled with the best appoximation of the solution if the solution can't be found
- int items; //number of nuggets to split
- cout << "How many nuggets do you want to buy? "; cin >> items;
- if (FillBoxes(Sizes,3,BoxCombination,BoxApprox,items)){
- cout << endl << "The items perfectly fit in:";
- for (int i=0;i<3;i++){
- cout << endl << BoxCombination[i] << " Boxes of size " << Sizes[i];
- }
- cout << endl;
- }
- else{
- int temp=0;
- cout << endl << "The items don't perfectly fit in the boxes."<<endl<<"The best appoximation is:";
- for (int i=0;i<3;i++){
- cout << endl << BoxApprox[i] << " Boxes of size " << Sizes[i];
- temp+=BoxApprox[i]*Sizes[i];
- }
- cout << endl << "That fits exactly " << temp << " items" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement