CARCHOICE - Editorial

PROBLEM LINK:

Contest Division 1
Contest Division 2
Contest Division 3
Contest Division 4

Setter: Nandeesh Gupta
Tester: Abhinav Sharma, Manan Grover
Editorialist: Lavish Gupta

DIFFICULTY:

Cakewalk

PREREQUISITES:

None

PROBLEM:

Chef is planning to buy a new car for his birthday. After a long search, he is left with 2 choices:

  • Car 1: Runs on diesel with a fuel economy of x_1 km/l
  • Car 2: Runs on petrol with a fuel economy of x_2 km/l

Chef also knows that

  • the current price of diesel is y_1 rupees per litre
  • the current price of petrol is y_2 rupees per litre

Assuming that both cars cost the same and that the price of fuel remains constant, which car will minimize Chef’s expenses?

Print your answer as a single integer in the following format

  • If it is better to choose Car 1, print -1
  • If both the cars will result in the same expenses, print 0
  • If it is better to choose Car 2, print 1

EXPLANATION:

Car 1: It runs on diesel with a fuel economy of x_1 km/l. Current price of diesel is y_1 rupees per litre. So, Car 1 requires y_1 rupees for x_1 kilometers - \frac{y_1}{x_1} rupees for one kilometer.

Car 2: It runs on petrol with a fuel economy of x_2 km/l. Current price of diesel is y_2 rupees per litre. So, Car 2 requires y_2 rupees for x_2 kilometers - \frac{y_2}{x_2} rupees for one kilometer.

Using the above information, we have

  • If \frac {y_1}{x_1} \lt \frac {y_2}{x_2}, then Car 1 is more economical, and answer should be -1.
  • If \frac {y_1}{x_1} = \frac {y_2}{x_2}, both cars are equally economical, and answer should be 0.
  • If \frac {y_1}{x_1} \gt \frac {y_2}{x_2}, then Car 2 is more economical, and answer should be 1.
Comparing two fractions

Suppose we want to compare two fractions - \frac{a}{b} and \frac{c}{d}. One of the ways is to store the values of these fraction in a floating point data type like float or double. However, this method sometime face precision issues.

Suppose we want to check if \frac{a}{b} < \frac{c}{d}.
\frac{a}{b} \lt \frac{c}{d} \implies a\cdot d \lt b \cdot c. So now, we can compare a \cdot d with b \cdot c, and this involves only integral calculations.

TIME COMPLEXITY:

O(1) for each test case.

SOLUTION:

Editorialist's Solution
#include<bits/stdc++.h>
#define ll long long
#define pll pair<ll ,ll>
using namespace std ;
const ll z = 998244353 ;


int main()
{

    int t ;
    cin >> t ;
    while(t--)
    {
        int x1 , x2 , y1 , y2 ;
        cin >> x1 >> x2 >> y1 >> y2 ;

        int ans = y1*x2 - y2*x1 ;

        if(ans < 0)
            ans = -1 ;
        if(ans > 0)
            ans = 1 ;

        cout << ans << endl ;
    }

    return 0;
}