classMultiSet: def__init__(self): self.data = dict() defadd(self, val): self.data[val] = 1 + (self.data[val] if val in self.data else0) defremove(self, val): ifnot val in self.data: return self.data[val] -= 1 if self.data[val] == 0: del self.data[val]
Fenwick Tree / Binary-indexed Tree
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classBIT: def__init__(self, size): self.size = size self.data = [0] * size defadd(self, pos, val): while pos < self.size: self.data[pos] += val pos += pos & (-pos) defquery(self, pos): res = 0 while pos > 0: res += self.data[pos] pos &= pos - 1 return res
DO NOT dividing an integer by another integer with respect to the modulus $mod$. To calculate $ n/m%mod $ correctly ($ mod$ is a prime number thus $ φ(mod)=mod-1 $). Use Eular function or modular multiplicative inversion.
Euler function $ φ(n) $
Quick greatest common divisor
1 2 3 4 5 6 7 8 9 10 11 12 13
defkgcd(a, b): if a == 0: return b if b == 0: return a if (a & 1) == 0and (b & 1) == 0: return kgcd(a >> 1, b >> 1) << 1 elif (b & 1) == 0: return kgcd(a, b >> 1) elif (a & 1) == 0: return kgcd(a >> 1, b) else: return kgcd(abs(a - b), min(a, b))
An enhanced InputReader supporting keeping reading data until the end of input while the number of input cases is unknown: 一个加强版的输入器 ,支持读到输入文件末尾的方式,用法类似java.util.Scanner但效率显著提高: