Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NumMatrix {
- Fenwick[] bit;
- public NumMatrix(int[][] matrix) {
- int m = matrix.length;
- bit = new Fenwick[m];
- for(int i = 0; i < m; i++)
- {
- bit[i] = new Fenwick(matrix[i]);
- System.out.println(Arrays.toString(bit[i].bit));
- }
- }
- public void update(int row, int col, int val) {
- bit[row].update(col + 1, val);
- }
- public int sumRegion(int row1, int col1, int row2, int col2) {
- int sum = 0;
- for(int i = row1; i <= row2; i++)
- {
- sum += bit[i].get(col2 + 1) - bit[i].get(col1);
- }
- return sum;
- }
- }
- class Fenwick
- {
- int[] bit;
- public Fenwick(int[] ary)
- {
- int n = ary.length, len = 1;
- while(len <= n) len <<= 1;
- bit = new int[len];
- for(int i = 0; i < n; i++) update(i + 1, ary[i]);
- }
- int get(int pos)
- {
- int res = 0;
- while(pos > 0)
- {
- res += bit[pos];
- pos -= pos & -pos;
- }
- return res;
- }
- void update(int pos, int val)
- {
- int cur = get(pos) - get(pos - 1), diff = -cur + val;
- int n = bit.length;
- while(pos < n)
- {
- bit[pos] += diff;
- pos += pos & -pos;
- }
- }
- }
- /**
- * Your NumMatrix object will be instantiated and called as such:
- * NumMatrix obj = new NumMatrix(matrix);
- * obj.update(row,col,val);
- * int param_2 = obj.sumRegion(row1,col1,row2,col2);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement