-
Notifications
You must be signed in to change notification settings - Fork 31
/
UnboundedKnapsackRemovable.py
56 lines (45 loc) · 1.81 KB
/
UnboundedKnapsackRemovable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from typing import List, Optional
class UnboundedKnapsackRemovable:
"""可撤销完全背包,用于求解方案数/可行性."""
__slots__ = "_dp", "_maxWeight", "_mod"
def __init__(self, maxWeight: int, mod: Optional[int] = None, dp: Optional[List[int]] = None):
if dp is not None:
self._dp = dp
else:
self._dp = [0] * (maxWeight + 1)
self._dp[0] = 1
self._maxWeight = maxWeight
self._mod = mod
def add(self, weight: int) -> None:
"""添加一个重量为weight的物品."""
dp = self._dp
if self._mod is None:
for i in range(weight, self._maxWeight + 1):
dp[i] += dp[i - weight]
else:
mod = self._mod
for i in range(weight, self._maxWeight + 1):
dp[i] = (dp[i] + dp[i - weight]) % mod
def remove(self, weight: int) -> None:
"""移除一个重量为weight的物品.需要保证weight物品存在."""
dp = self._dp
if self._mod is None:
for i in range(self._maxWeight, weight - 1, -1):
dp[i] -= dp[i - weight]
else:
mod = self._mod
for i in range(self._maxWeight, weight - 1, -1):
dp[i] = (dp[i] - dp[i - weight]) % mod
def query(self, weight: int) -> int:
"""
查询组成重量为weight的物品有多少种方案.
!注意需要特判重量为0.
"""
return self._dp[weight] if 0 <= weight <= self._maxWeight else 0
def copy(self) -> "UnboundedKnapsackRemovable":
return UnboundedKnapsackRemovable(self._maxWeight, self._mod, self._dp[:])
def __repr__(self) -> str:
return self._dp.__repr__()
if __name__ == "__main__":
# https://atcoder.jp/contests/agc049/tasks/agc049_d
...