forked from NASU41/AtCoderLibraryForJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiset.java
More file actions
32 lines (32 loc) · 927 Bytes
/
Multiset.java
File metadata and controls
32 lines (32 loc) · 927 Bytes
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
class Multiset<T> extends java.util.TreeMap<T,Long>{
public Multiset(){
super();
}
public Multiset(java.util.List<T> list){
super();
for(T e: list) this.addOne(e);
}
public long count(Object elm){
return getOrDefault(elm,0L);
}
public void add(T elm, long amount){
if(!this.containsKey(elm)) put(elm, amount);
else replace(elm, get(elm)+amount);
if(this.count(elm)==0) this.remove(elm);
}
public void addOne(T elm){
this.add(elm, 1);
}
public void removeOne(T elm){
this.add(elm, -1);
}
public void removeAll(T elm){
this.add(elm, -this.count(elm));
}
public static<T> Multiset<T> merge(Multiset<T> a, Multiset<T> b){
Multiset<T> c = new Multiset<>();
for(T x: a.keySet()) c.add(x, a.count(x));
for(T y: b.keySet()) c.add(y, b.count(y));
return c;
}
}