File tree 1 file changed +76
-0
lines changed
1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ class BIT {
2
+ constructor ( n ) {
3
+ this . arr = new Array ( n + 1 ) . fill ( 0 )
4
+ }
5
+
6
+ update ( i , v ) {
7
+ while ( i < this . arr . length ) {
8
+ this . arr [ i ] += v
9
+ i += i & - i
10
+ }
11
+ }
12
+
13
+ prefixSum ( i ) {
14
+ let res = 0
15
+ while ( i > 0 ) {
16
+ res += this . arr [ i ]
17
+ i -= i & - i
18
+ }
19
+ return res
20
+ }
21
+
22
+ upper_bound ( v ) {
23
+ const n = Math . floor ( Math . log2 ( this . arr . length ) )
24
+ let pos = 0
25
+ let s = 0
26
+ for ( let i = n ; i >= 0 ; i -- ) {
27
+ if (
28
+ pos + ( 1 << i ) < this . arr . length &&
29
+ s + this . arr [ pos + ( 1 << i ) ] <= v
30
+ ) {
31
+ pos += 1 << i
32
+ s += this . arr [ pos ]
33
+ }
34
+ }
35
+ return pos + 1
36
+ }
37
+ }
38
+
39
+ class MKAverage {
40
+ constructor ( m , k ) {
41
+ this . m = m
42
+ this . k = k
43
+ this . cnt = new BIT ( 10 ** 5 )
44
+ this . bit = new BIT ( 10 ** 5 )
45
+ this . q = [ ]
46
+ }
47
+
48
+ addElement ( num ) {
49
+ this . q . push ( num )
50
+ this . cnt . update ( num , 1 )
51
+ this . bit . update ( num , num )
52
+ if ( this . q . length > this . m ) {
53
+ const x = this . q . shift ( )
54
+ this . cnt . update ( x , - 1 )
55
+ this . bit . update ( x , - x )
56
+ }
57
+ }
58
+
59
+ calculateMKAverage ( ) {
60
+ if ( this . q . length < this . m ) {
61
+ return - 1
62
+ }
63
+ const l = this . k
64
+ const r = this . m - this . k
65
+ const i = this . cnt . upper_bound ( l )
66
+ const j = this . cnt . upper_bound ( r )
67
+ let ans = this . bit . prefixSum ( j ) - this . bit . prefixSum ( i )
68
+ ans += ( this . cnt . prefixSum ( i ) - l ) * i
69
+ ans -= ( this . cnt . prefixSum ( j ) - r ) * j
70
+ return Math . floor ( ans / ( this . m - 2 * this . k ) )
71
+ }
72
+ }
73
+
74
+ // another
75
+
76
+
1
77
/**
2
78
* @param {number } m
3
79
* @param {number } k
You can’t perform that action at this time.
0 commit comments