Problem Statement
題目簡述
超市以兩個平行陣列 products \textit{products} products 、prices \textit{prices} prices 表示商品編號與單價。每位顧客結帳時以平行陣列 product \textit{product} product 、amount \textit{amount} amount 表示購買的商品與數量,小計為 ∑ j amount [ j ] × ( 第 j 項商品的單價 ) \sum_j \textit{amount}[j] \times (\text{第 } j \text{ 項商品的單價}) ∑ j amount [ j ] × ( 第 j 項商品的單價 ) 。
每第 n n n 位結帳的顧客可享 discount % \textit{discount}\% discount % 折扣,即實付 bill × 100 − discount 100 \textit{bill} \times \dfrac{100 - \textit{discount}}{100} bill × 1 0 0 1 0 0 − discount 。
實作 Cashier 類別:
Cashier(n, discount, products, prices):初始化。
getBill(product, amount):回傳本次顧客(套用折扣後)的實付金額,與正確值誤差在 1 0 − 5 10^{-5} 1 0 − 5 內即可。
Constraints
約束條件
1 ≤ n ≤ 1 0 4 1 \le n \le 10^4 1 ≤ n ≤ 1 0 4
0 ≤ discount ≤ 100 0 \le \textit{discount} \le 100 0 ≤ discount ≤ 1 0 0
1 ≤ products.length ≤ 200 1 \le \textit{products.length} \le 200 1 ≤ products.length ≤ 2 0 0
prices.length = products.length \textit{prices.length} = \textit{products.length} prices.length = products.length
1 ≤ products [ i ] ≤ 200 1 \le \textit{products}[i] \le 200 1 ≤ products [ i ] ≤ 2 0 0
1 ≤ prices [ i ] ≤ 1000 1 \le \textit{prices}[i] \le 1000 1 ≤ prices [ i ] ≤ 1 0 0 0
products \textit{products} products 中的元素互不相同
1 ≤ product.length ≤ products.length 1 \le \textit{product.length} \le \textit{products.length} 1 ≤ product.length ≤ products.length
amount.length = product.length \textit{amount.length} = \textit{product.length} amount.length = product.length
product [ j ] \textit{product}[j] product [ j ] 必定存在於 products \textit{products} products 中
1 ≤ amount [ j ] ≤ 1000 1 \le \textit{amount}[j] \le 1000 1 ≤ amount [ j ] ≤ 1 0 0 0
product \textit{product} product 中的元素互不相同
最多呼叫 1000 1000 1 0 0 0 次 getBill
答案與正確值誤差在 1 0 − 5 10^{-5} 1 0 − 5 內即視為正確
思路:雜湊表 + 計數器
需要維護的狀態只有兩件事:
商品編號到單價的對應 :初始化時建立雜湊表 priceMap \textit{priceMap} priceMap ,之後每次查價都是 O ( 1 ) \mathcal{O}(1) O ( 1 ) 。
目前是第幾位顧客 :用計數器 cnt \textit{cnt} cnt 記錄,每次 getBill 先加一。
結帳時依雜湊表算出小計;若 cnt \textit{cnt} cnt 是 n n n 的倍數,就乘上預先算好的折扣係數 1 − discount 100 1 - \dfrac{\textit{discount}}{100} 1 − 1 0 0 discount 。
複雜度分析
時間複雜度:初始化 O ( m ) \mathcal{O}(m) O ( m ) ,每次 getBill 為 O ( k ) \mathcal{O}(k) O ( k ) ,其中 m m m 為 products \textit{products} products 的長度、k k k 為本次 product \textit{product} product 的長度。
空間複雜度:O ( m ) \mathcal{O}(m) O ( m ) ,雜湊表的大小。
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 class Cashier : def __init__ (self, n: int , discount: int , products: list [int ], prices: list [int ] ): self.n = n self.cnt = 0 self.discount = 1 - discount / 100 self.priceMap = {p: price for p, price in zip (products, prices)} def getBill (self, product: list [int ], amount: list [int ] ) -> float : self.cnt += 1 total = sum (self.priceMap[p] * a for p, a in zip (product, amount)) if self.cnt % self.n == 0 : total *= self.discount return total