Khái niệm
Cho khoảng chi phí từ lowCost đến upCost và khoảng số lượng từ lowQuant đến upQuant, xác định xem có thể đạt được tỷ lệ r cho trước với r = cost/quantity, và lowCost <= cost <= upCost, lowQuant <= quantity <= upQuant.
Đầu vào
lowCost = 2, upCost = 10, lowQuant = 3, upQuant = 9 r = 3
Đầu ra
Yes
Giải thích
cost = r * quantity = 3 * 3 = 9, cost nằm trong [1, 10], quantity nằm trong [2, 8]
Đầu vào
lowCost = 15, upCost = 31, lowQuant = 6, upQuant = 13 r = 8
Đầu ra
No
Giải thích
cost = r * quantity = 8 * 6 = 48, cost không nằm trong [15, 31] dù quantity nằm trong [6, 13]
Phương pháp
Từ công thức: cost = quantity * r. Với mỗi giá trị quantity trong khoảng, tính cost = quantity * r. Nếu cost nào nằm trong [lowCost, upCost] thì trả về Yes, ngược lại No.
Ví dụ
// Chương trình C++ kiểm tra khả năng đạt tỷ lệ r
#include <bits/stdc++.h>
using namespace std;
bool isRatioPossible1(int lowCost1, int upCost1, int lowQuant1, int upQuant1, int r1){
for (int i = lowQuant1; i <= upQuant1; i++){
int ans1 = i * r1;
if (lowCost1 <= ans1 && ans1 <= upCost1)
return true;
}
return false;
}
int main(){
int lowCost1 = 2, upCost1 = 10, lowQuant1 = 3, upQuant1 = 9, r1 = 3;
if (isRatioPossible1(lowCost1, upCost1, lowQuant1, upQuant1, r1))
cout << "Yes";
else
cout << "No";
return 0;
}
Đầu ra
Yes