Buy 2 Get 1 Free codechef solution in c++

The "Buy 2 Get 1 Free" problem on CodeChef can be solved using the following C++ code:

#include <iostream>
using namespace std;

int main() {
    int t;
    cin >> t;

    while (t--) {
        int x, y, z;
        cin >> x >> y >> z;

        int totalBooks = x + y + z;
        int minPrice = min(min(x, y), z);
        int discount = minPrice / 2;

        int finalPrice = totalBooks * minPrice - discount;
        cout << finalPrice << endl;
    }

    return 0;
}

Explanation:

  1. We start by including the necessary header file iostream to enable input/output operations.

  2. Inside the main() function, we declare an integer variable t to store the number of test cases. We use cin to read the value of t from the user.

  3. We then enter a while loop that runs t times, as specified by the user.

  4. Inside the loop, we declare three integer variables x, y, and z to store the quantities of books in three categories. We use cin to read the values of x, y, and z from the user.

  5. Next, we calculate the total number of books by adding x, y, and z together and store it in the variable totalBooks.

  6. We find the minimum quantity among x, y, and z using the min() function and store it in the variable minPrice.

  7. Since the offer is "Buy 2 Get 1 Free," we calculate the discount by dividing minPrice by 2 and store it in the variable discount.

  8. Finally, we calculate the final price by multiplying totalBooks with minPrice and subtracting the discount. The result is stored in the variable finalPrice.

  9. We use cout to print the value of finalPrice followed by a new line.

  10. The loop continues until all test cases are processed.

  11. The return 0; statement ends the program.

This code solves the "Buy 2 Get 1 Free" problem by calculating the final price after applying the discount.