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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//! 多重集合。

use std::collections::{btree_map::Iter as BTreeMapIter, BTreeMap};
use std::fmt::{self, Debug};

/// 多重集合。
#[derive(Clone, Eq, PartialEq)]
pub struct BTreeMultiset<K>(BTreeMap<K, usize>, usize);

impl<K: Ord> BTreeMultiset<K> {
    pub fn new() -> Self { Self(BTreeMap::new(), 0) }
    pub fn insert(&mut self, k: K) { self.insert_n(k, 1) }
    pub fn insert_n(&mut self, k: K, n: usize) {
        if n == 0 {
            return;
        }
        *self.0.entry(k).or_insert(0) += n;
        self.1 += n;
    }
    pub fn remove(&mut self, k: &K) { self.remove_n(k, 1) }
    pub fn remove_n(&mut self, k: &K, n: usize) {
        if n == 0 {
            return;
        }
        match self.0.get(k) {
            Some(&c) if c <= n => {
                self.0.remove(&k);
                self.1 -= c;
            }
            Some(_) => {
                *self.0.get_mut(k).unwrap() -= n;
                self.1 -= n;
            }
            None => {}
        }
    }
    pub fn min(&self) -> Option<&K> { self.0.keys().next() }
    pub fn max(&self) -> Option<&K> { self.0.keys().next_back() }
    pub fn is_empty(&self) -> bool { self.0.is_empty() }
    pub fn len(&self) -> usize { self.1 }
    pub fn count(&self, k: &K) -> usize { *self.0.get(k).unwrap_or(&0) }

    pub fn iter(&self) -> Iter<'_, K> { Iter::new(self) }
}

pub struct Iter<'a, K: 'a> {
    iter: BTreeMapIter<'a, K, usize>,
    key: Option<&'a K>,
    count: usize,
}

impl<'a, K: 'a + Ord> Iter<'a, K> {
    pub fn new(ms: &'a BTreeMultiset<K>) -> Self {
        let mut iter = ms.0.iter();
        if let Some((key, &count)) = iter.next() {
            Self { iter, key: Some(key), count }
        } else {
            Self { iter, key: None, count: 0 }
        }
    }
}

impl<'a, K: 'a> Iterator for Iter<'a, K> {
    type Item = &'a K;
    fn next(&mut self) -> Option<&'a K> {
        if self.key.is_none() {
            return None;
        }

        if self.count > 0 {
            self.count -= 1;
        } else if let Some((k, &v)) = self.iter.next() {
            self.key = Some(k);
            self.count = v - 1;
        } else {
            self.key = None;
        }
        self.key
    }
}

impl<'a, K: Ord> IntoIterator for &'a BTreeMultiset<K> {
    type Item = &'a K;
    type IntoIter = Iter<'a, K>;
    fn into_iter(self) -> Self::IntoIter { self.iter() }
}

impl<K: Debug> Debug for BTreeMultiset<K> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_map().entries(self.0.iter()).finish()
    }
}

#[test]
fn test_debug_fmt() {
    let mut ms = BTreeMultiset::new();
    ms.insert(5);
    ms.insert(5);
    ms.insert(7);
    ms.insert_n(4, 0);
    ms.remove_n(&3, 0);
    assert_eq!(format!("{:?}", ms), "{5: 2, 7: 1}");
}

#[test]
fn test_iter() {
    let mut ms = BTreeMultiset::new();
    ms.insert(5);
    ms.insert(5);
    ms.insert(6);
    ms.insert(6);
    ms.insert(6);
    ms.insert(7);
    ms.insert_n(4, 0);
    ms.remove_n(&3, 0);
    assert_eq!(ms.iter().copied().collect::<Vec<_>>(), [5, 5, 6, 6, 6, 7]);
}

#[test]
fn test_count() {
    let mut ms = BTreeMultiset::new();
    assert_eq!(ms.len(), 0);

    ms.insert_n(5, 2);
    assert_eq!(ms.len(), 2);
    assert_eq!(ms.count(&5), 2);
    assert_eq!(ms.count(&4), 0);

    ms.remove_n(&5, 3);
    assert_eq!(ms.len(), 0);
    assert_eq!(ms.count(&5), 0);
    assert_eq!(ms.count(&4), 0);
}