File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ package followup ;
2
+
3
+ public class IndexTreeTest {
4
+
5
+ public static class IndexTree {
6
+
7
+ private int [] tree ;
8
+ private int N ;
9
+
10
+ public IndexTree (int size ) {
11
+ N = size ;
12
+ tree = new int [N + 1 ];
13
+ }
14
+
15
+ public int sum (int index ) {
16
+ int ret = 0 ;
17
+ while (index > 0 ) {
18
+ ret += tree [index ];
19
+ index -= index & -index ;
20
+ }
21
+ return ret ;
22
+ }
23
+
24
+ public void add (int index , int d ) {
25
+ while (index <= N ) {
26
+ tree [index ] += d ;
27
+ index += index & -index ;
28
+ }
29
+ }
30
+ }
31
+
32
+ public static class Right {
33
+ private int [] nums ;
34
+ private int N ;
35
+
36
+ public Right (int size ) {
37
+ N = size + 1 ;
38
+ nums = new int [N + 1 ];
39
+ }
40
+
41
+ public int sum (int index ) {
42
+ int ret = 0 ;
43
+ for (int i = 1 ; i <= index ; i ++) {
44
+ ret += nums [i ];
45
+ }
46
+ return ret ;
47
+ }
48
+
49
+ public void add (int index , int d ) {
50
+ nums [index ] += d ;
51
+ }
52
+
53
+ }
54
+
55
+ public static void main (String [] args ) {
56
+ int N = 100 ;
57
+ int V = 100 ;
58
+ int testTime = 2000000 ;
59
+ IndexTree tree = new IndexTree (N );
60
+ Right test = new Right (N );
61
+ System .out .println ("test begin" );
62
+ for (int i = 0 ; i < testTime ; i ++) {
63
+ int index = (int ) (Math .random () * N ) + 1 ;
64
+ if (Math .random () <= 0.5 ) {
65
+ int add = (int ) (Math .random () * V );
66
+ tree .add (index , add );
67
+ test .add (index , add );
68
+ } else {
69
+ if (tree .sum (index ) != test .sum (index )) {
70
+ System .out .println ("Oops!" );
71
+ }
72
+ }
73
+ }
74
+ System .out .println ("test finish" );
75
+ }
76
+
77
+ }
You can’t perform that action at this time.
0 commit comments