File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
algorithm-constent-template/src/com/fqh Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -15,6 +15,7 @@ public static void main(String[] args) {
1515 }
1616}
1717
18+ // ST表维护区间最值
1819class SparseTable {
1920 private int [][] st ; // st[i][j] 表示区间 [i, i + 2^j - 1] 的最大值
2021 private int [] log ;
@@ -47,4 +48,49 @@ public int query(int L, int R) {
4748 int j = log [R - L + 1 ];
4849 return Math .max (st [L ][j ], st [R - (1 << j ) + 1 ][j ]);
4950 }
51+ }
52+
53+ // ST表维护区间GCD
54+ class SparseTableGCD {
55+ private int [][] st ; // st[i][j] 表示区间 [i, i + 2^j - 1] 的最大值
56+ private int [] log ;
57+ private int n ;
58+
59+ public SparseTableGCD (int [] arr ) {
60+ n = arr .length ;
61+ int logN = Integer .highestOneBit (n ) * 2 - 1 ; // log2(n)
62+ log = new int [n + 1 ];
63+ st = new int [n ][20 ];
64+
65+ for (int i = 2 ; i <= n ; i ++) {
66+ log [i ] = log [i / 2 ] + 1 ;
67+ }
68+
69+ for (int i = 0 ; i < n ; i ++) {
70+ st [i ][0 ] = arr [i ];
71+ }
72+
73+ // 构建 st表
74+ for (int j = 1 ; (1 << j ) <= n ; j ++) {
75+ for (int i = 0 ; i + (1 << j ) - 1 < n ; i ++) {
76+ st [i ][j ] = gcd (st [i ][j - 1 ], st [i + (1 << (j - 1 ))][j - 1 ]);
77+ }
78+ }
79+ }
80+
81+ // 查询区间 [L, R] 的最大值
82+ public int query (int L , int R ) {
83+ int j = log [R - L + 1 ];
84+ return gcd (st [L ][j ], st [R - (1 << j ) + 1 ][j ]);
85+ }
86+
87+ // 计算两个数的 GCD
88+ public int gcd (int a , int b ) {
89+ while (b != 0 ) {
90+ int temp = b ;
91+ b = a % b ;
92+ a = temp ;
93+ }
94+ return a ;
95+ }
5096}
You can’t perform that action at this time.
0 commit comments