Non Built-in Data Structures And Algorithms in Python3

Unordered MultiSet

1
2
3
4
5
6
7
8
9
10
11
12
13
class MultiSet:
def __init__(self):
self.data = dict()

def add(self, val):
self.data[val] = 1 + (self.data[val] if val in self.data else 0)

def remove(self, val):
if not 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
class BIT:
def __init__(self, size):
self.size = size
self.data = [0] * size

def add(self, pos, val):
while pos < self.size:
self.data[pos] += val
pos += pos & (-pos)

def query(self, pos):
res = 0
while pos > 0:
res += self.data[pos]
pos &= pos - 1
return res
Read more

Universal Code Competition Template in Python3 (editing) [2022]

Number Theory

Quick power and modulo

To calculate $ n^m % mod $:

Division and modulo

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
def kgcd(a, b):
if a == 0:
return b
if b == 0:
return a
if (a & 1) == 0 and (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))
Read more

ACM竞赛Java模板[dev-160504]

ACM-ICPC

Java Code Template By Semprathlon

  • 部分理论知识引用自维基百科

Input 输入

An enhanced InputReader supporting keeping reading data until the end of input while the number of input cases is unknown:
一个加强版的输入器 ,支持读到输入文件末尾的方式,用法类似java.util.Scanner但效率显著提高:

Read more