1
+ package IndexedTree .P1275 ;
2
+
3
+ import java .io .*;
4
+ import java .util .*;
5
+
6
+ public class Main {
7
+
8
+ static int N , Q ;
9
+ static int [] nums ;
10
+
11
+ public static void main (String [] args ) throws Exception {
12
+ System .setIn (new FileInputStream ("src/IndexedTree/P1275/input.txt" ));
13
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
14
+ StringTokenizer st = new StringTokenizer (br .readLine ());
15
+
16
+ N = stoi (st .nextToken ());
17
+ Q = stoi (st .nextToken ());
18
+
19
+ nums = new int [N ];
20
+ st = new StringTokenizer (br .readLine ());
21
+ for (int i = 0 ; i < N ; i ++) nums [i ] = stoi (st .nextToken ());
22
+
23
+ SegmentTree tree = new SegmentTree (N , nums );
24
+
25
+ while (Q -- > 0 ) {
26
+ st = new StringTokenizer (br .readLine ());
27
+ int x = stoi (st .nextToken ()), y = stoi (st .nextToken ());
28
+ int a = stoi (st .nextToken ()), b = stoi (st .nextToken ());
29
+ System .out .println (tree .sum (1 , 1 , N , x , y ));
30
+ tree .update (1 , 1 , N , a , b );
31
+ }
32
+ }
33
+
34
+ private static int stoi (String s ) { return Integer .parseInt (s ); }
35
+ }
36
+
37
+ class SegmentTree {
38
+ long [] tree ;
39
+ int [] arr ;
40
+
41
+ public SegmentTree (int N , int [] arr ) {
42
+ tree = new long [(int ) Math .pow (2 , Math .ceil (Math .log (N ) / Math .log (2 )) + 1 )];
43
+ this .arr = arr ;
44
+ makeTree (1 , 1 , N );
45
+ }
46
+
47
+ private void makeTree (int idx , int start , int end ) {
48
+ if (start == end ) {
49
+ tree [idx ] = arr [start -1 ];
50
+ return ;
51
+ }
52
+ int mid = (start + end ) / 2 ;
53
+ makeTree (idx *2 , start , mid );
54
+ makeTree (idx *2 +1 , mid +1 , end );
55
+ tree [idx ] = tree [idx *2 ] + tree [idx *2 +1 ];
56
+ }
57
+
58
+ public long sum (int idx , int start , int end , int x , int y ) {
59
+ if (x > y ) {
60
+ return sum (idx , start , end , y , x );
61
+ } else {
62
+ if (end < x || start > y ) return 0 ;
63
+ if (x <= start && end <= y ) return tree [idx ];
64
+ int mid = (start + end ) / 2 ;
65
+ return sum (idx *2 , start , mid , x , y ) + sum (idx *2 +1 , mid +1 , end , x , y );
66
+ }
67
+ }
68
+
69
+ public void update (int idx , int start , int end , int a , int b ) {
70
+ if (end < a || start > a ) return ;
71
+ if (start == end ) {
72
+ tree [idx ] = b ;
73
+ return ;
74
+ }
75
+ int mid = (start + end ) / 2 ;
76
+ update (idx *2 , start , mid , a , b );
77
+ update (idx *2 +1 , mid +1 , end , a , b );
78
+ tree [idx ] = tree [idx *2 ] + tree [idx *2 +1 ];
79
+ }
80
+ }
0 commit comments