ออกแบบ Class **Cashier** สำหรับซูเปอร์มาร์เก็ต:
- Constructor:
Cashier(int n, int discount, vector<int> products, vector<int> prices)n: ทุกnCustomer ได้ส่วนลดdiscount: เปอร์เซ็นต์ลด (เช่น 50 = 50%)products[i]: Product ID,prices[i]: ราคาต่อหน่วย
getBill(vector<int> product, vector<int> amount): คำนวณ Bill, ให้ส่วนลดถ้าเป็น Customer คนที่n
ตัวอย่าง
Cashier(3, 50, [1,2,3,4,5,6,7], [100,200,300,400,300,200,100]) getBill([1,2], [1,2]) -> 1*100 + 2*200 = 500.0 (Customer 1, No Discount) getBill([3,7], [10,10]) -> 10*300 + 10*100 = 4000.0 (Customer 2, No Discount) getBill([1..7], [1..1]) -> Sum = 1600, Discount 50% -> 800.0 (Customer 3, Discount!) getBill([4], [10]) -> 10*400 = 4000.0 (Customer 4 -> Reset, No Discount) ...
แนวทาง: Counter + Hash Map Price Lookup
- Map
price[productID] = priceสำหรับ O(1) Lookup - Counter
customerCountนับ Customer (Modulon) getBill:customerCount++- คำนวณ
total = sum(price[p] * amount) - ถ้า
customerCount == n-> Apply Discount,customerCount = 0 - Return Total
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
class Cashier {
public:
int n, discount, customerCount;
unordered_map<int, double> priceMap;
Cashier(int n, int discount, vector<int>& products, vector<int>& prices) {
this->n = n;
this->discount = discount;
customerCount = 0;
for (int i = 0; i < products.size(); i++)
priceMap[products[i]] = prices[i];
}
double getBill(vector<int>& product, vector<int>& amount) {
customerCount++;
bool applyDiscount = (customerCount == n);
if (applyDiscount) customerCount = 0;
double total = 0;
for (int i = 0; i < product.size(); i++) {
total += priceMap[product[i]] * amount[i];
}
if (applyDiscount) total -= total * discount / 100.0;
return total;
}
};
Input / Output
Input: See main() - Series of getBill calls Output: 500.0 4000.0 800.0 4000.0 4000.0 7350.0 2500.0
ความซับซ้อน (Complexity)
- Constructor: O(P) — P = Number of Products
- getBill: O(M) — M = Number of Items in Bill
- Space: O(P) — Price Map
Design Pattern: **Stateful Service Class** พร้อม Counter และ Lookup Map ครับ