Mô tả bài toán
Cho hai số nguyên tomatoSlices (miếng cà chua) và cheeseSlices (miếng phô mai). Có hai loại burger:
- Jumbo Burger: 4 miếng cà chua + 1 miếng phô mai.
- Small Burger: 2 miếng cà chua + 1 miếng phô mai.
Hãy tìm [total_jumbo, total_small] sao cho sau khi làm burger, số miếng cà chua và phô mai còn lại đều bằng 0. Nếu không thể, trả về mảng rỗng.
Ví dụ: tomatoSlices = 16, cheeseSlices = 7 → kết quả [1, 6] (1 Jumbo + 6 Small = 4×1 + 2×6 = 16 cà chua, 1 + 6 = 7 phô mai).
Giải thuật
- Nếu
tomatolẻ, hoặccheese > tomato/2, hoặctomato > 4*cheese→ trả về rỗng. - Tính
x = (4 * cheese - tomato) / 2(số Small burger). - Tính
y = (tomato - 2*x) / 4(số Jumbo burger). - Trả về
[y, x].
Cài đặt C++
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v) {
cout << "[";
for (int i = 0; i < v.size(); i++) {
cout << v[i] << ", ";
}
cout << "]" << endl;
}
class Solution {
public:
vector<int> numOfBurgers(int t, int c) {
vector<int> ans;
if (t % 2 != 0 || c > t/2 || t > c*4) return ans;
int x = (4 * c - t) / 2;
int y = (t - 2 * x) / 4;
ans.push_back(y);
ans.push_back(x);
return ans;
}
};
int main() {
Solution ob;
print_vector(ob.numOfBurgers(16, 7));
return 0;
}
Đầu vào / Đầu ra
Input: 16 7
Output: [1, 6]