Giả sử có chương trình giảm giá mỗi n khách hàng. Có các sản phẩm với id products[i] và giá prices[i]. Hệ thống đếm khách hàng, khi khách thứ n đến sẽ được giảm giá trên hóa đơn, sau đó đếm lại từ đầu. Khách hàng đặt hàng với product[i] là id sản phẩm, amount[i] là số lượng. Triển khai lớp Cashier với:
Cashier(int n, int discount, int[] products, int[] prices): Khởi tạo với n, discount, products, prices.
double getBill(int[] product, int[] amount): Trả về giá trị hóa đơn, áp dụng giảm giá nếu cần. Sai số 10^-5 được chấp nhận.
Ví dụ: Cashier(3, 50, [1,2,3,4,5,6,7], [100,200,300,400,300,200,100]). Các lời gọi getBill cho kết quả [500.0, 4000.0, 800.0, 4000.0, 4000.0, 7350.0, 2500.0].
Để giải quyết, chúng ta làm theo các bước:
Định nghĩa map order.
Constructor: curr = 0; order[products[i]] = prices[i]; lưu n, discount.
getBill: curr++; flag = (curr == n); nếu curr == n thì curr = 0; ret = 0; với mỗi sản phẩm: ret += order[product[i]] * amount[i]; nếu flag: ret -= ret * discount / 100; trả về ret.
Ví dụ (C++)
Hãy xem triển khai sau để hiểu rõ hơn:
#include <bits/stdc++.h>
using namespace std;
class Cashier {
public:
int curr;
map <double, double> order;
int n;
int discount;
Cashier(int n, int discount, vector<int>& pro, vector<int>& p) {
curr = 0;
for(int i = 0; i < p.size(); i++){
order[pro[i]] = p[i];
}
this->n = n;
this->discount = discount;
}
double getBill(vector<int> pro, vector<int> am) {
curr++;
bool flag = curr == n;
if(curr == n){
curr = 0;
}
double ret = 0;
for(int i = 0; i < pro.size(); i++){
double x = pro[i];
double cost = order[x];
double y = am[i];
ret += (cost * y);
}
if(flag) ret = ret - (ret * discount) / 100;
return ret;
}
};
int main(){
vector<int> v1 = {1,2,3,4,5,6,7}, v2 = {100,200,300,400,300,200,100};
Cashier ob(3, 50, v1, v2);
v1 = {1,2}, v2 = {1,2};
cout << (ob.getBill(v1, v2)) << endl;
v1 = {3,7}, v2 = {10,10};
cout << (ob.getBill(v1, v2)) << endl;
v1 = {1,2,3,4,5,6,7}, v2 = {1,1,1,1,1,1,1};
cout << (ob.getBill(v1, v2)) << endl;
v1 = {4}, v2 = {10};
cout << (ob.getBill(v1, v2)) << endl;
v1 = {7,3}, v2 = {10,10};
cout << (ob.getBill(v1, v2)) << endl;
v1 = {7,5,3,1,6,4,2}, v2 = {10,10,10,9,9,9,7};
cout << (ob.getBill(v1, v2)) << endl;
v1 = {2,3,5}, v2 = {5,2,3};
cout << (ob.getBill(v1, v2)) << endl;
}
Đầu vào
Xem hàm main
Đầu ra
500 4000 800 4000 4000 7350 2500