Sunday, 11 January 2015

Hackerrank Taum and B'day solution

Problem Statement:
Taum is planning to celebrate the birthday of his friend Diksha. There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy B number of black gifts and W number of white gifts.
  • The cost of each black gift is X units
  • and the cost of every white gift is Y units
  • and the cost of converting each black gift into white or white into black is Z units.
Help Taum by deducing the minimum amount he needs to spend on Diksha's gifts?
Input Format
The first line will contain an integer T which will be the number of test cases.
There will be T pair of lines. The first line of each test case will contain the value of integers B and W. Another line of each test will contain the value of integers X,Y and Z.
Constraints
1T10
0X,Y,Z,B,W109
Output Format
T lines each containing output for a particular test case.
Sample Input
1
10 10
1 1 1
Sample Output
20
Explanation
There is no benefit in converting the white gift into the black or the black gift into the white, So He will have to buy each gift for 1 unit.
Source Code:
 #include <cmath>  
 #include <cstdio>  
 #include <vector>  
 #include <iostream>  
 #include <algorithm>  
 using namespace std;  
 int main() {  
   /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
   unsigned long long t,b,w,x,y,z,i,j,k,costofb,costofw;  
   cin>>t;  
   while(t--){  
     cin>>b>>w;  
     cin>>x>>y>>z;  
     costofb = b*x;  
     costofw = w*y;  
     if(x==y){  
       cout<<costofb+costofw<<endl;  
     }else if(x<y){  
       if((x+z)<y){  
         cout<<((w*x)+(w*z))+costofb<<endl;  
       }else{  
         cout<<costofb+costofw<<endl;  
       }  
     }else{  
       if((y+z)<x){  
         cout<<((b*y)+(b*z))+costofw<<endl;  
       }else{  
         cout<<costofb+costofw<<endl;  
       }  
     }  
   }  
   return 0;  
 }  
** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

3 comments:

  1. Further Hackerrank Solutions can be found in the following link:
    http://fantabulouscode.blogspot.in/

    ReplyDelete
  2. Thanks for posting, I think finding min of x and y+z will be easier, posting what i used.
    int main() {
    int T = 0;

    std::cin >> T;

    for(;T--;) {
    unsigned long B, W, X, Y, Z = 0;
    std::cin >> B >> W;
    std::cin >> X >> Y >> Z;
    unsigned long a = std::min(X, Z+Y);
    unsigned long b = std::min(Y, Z+X);
    //std::cout << "a: " << a << " b: " << b << " X: " << X << " Y: " << Y << " Z: " << Z << std::endl;
    std::cout << B * a + W * b << std::endl;
    }
    return 0;
    }

    ReplyDelete