Fenwick Tree ( JAVA )

김현준·2023년 6월 25일
0

알고리즘

목록 보기
15/17

2042 : 구간 합 구하기

import static java.lang.Integer.*;

import java.io.*;
import java.util.*;

class Fenwick {

    long[] tree; // tree 배열도 long 으로 선언.
    int size;

    public Fenwick(int size) {
        this.size = size;
        tree = new long[size+1];
    }

    private long prefixSum(int i) {
        long ans = 0;
        while (i>0) {
            ans += tree[i];
            i -=  i & -i;
        }
        return ans;
    }

    public void update(int i , long diff) {
        while (i <= size) {
            tree[i] += diff;
            i += i & -i;
        }
    }

    public long intervalSum(int start , int end) {
        return prefixSum(end) - prefixSum(start-1);
    }
}
public class main90 {

    static int N,M,K;
    static long a,b,c;
    static long[] list;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st;
        st = new StringTokenizer(br.readLine());
        N = parseInt(st.nextToken());
        Fenwick fenwick = new Fenwick(N+1);
        M = parseInt(st.nextToken());
        K = parseInt(st.nextToken());

        list = new long[N+1];
        for (int i = 1 ; i <= N ; i++) {
            list[i] = Long.parseLong(br.readLine());
            fenwick.update(i , list[i]);
        }


        for (int i = 0 ; i < M+K ; i++) {
            st = new StringTokenizer(br.readLine());
            a = Long.parseLong(st.nextToken());
            b = Long.parseLong(st.nextToken());
            c = Long.parseLong(st.nextToken());

            if (a==1) {
                fenwick.update((int)b,c-list[(int)b]);
                list[(int)b] = c;
            } else {
                bw.write(Long.toString(fenwick.intervalSum((int) b, (int) c))+'\n');
            }
        }
        bw.flush();
    }
}
profile
울산대학교 IT융합학부 22학번

0개의 댓글